136. Single Number

85 阅读1分钟

题目描述

Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:
Input: [2,2,1]
Output: 1

Example 2:
Input: [4,1,2,1,2]
Output: 4

解题思路1: 暴力破解

首先这个题目可以暴力破解, 使用hash记录每个值出现的次数, 最后在拿到只出现一次那个数字
时间复杂度: O(n)

示例代码1:

func singleNumber(_ nums: [Int]) -> Int {

    var hash: [Int: Int] = [:]
    for n in nums {
        let time = hash[n]
        if time == nil {
            hash[n] = 1
        }else {
            hash.updateValue(time! + 1, forKey: n)
        }
    }
    var result = 0
    hash.forEach { (m) in
        if m.value == 1 {
            result = m.key
        }
    }
    return result
}

解题思路2: 位运算

因为题目中提到, 除了结果意外,其他数字都是出现2次,我们就可以使用 异或^ 来做, 因为2个相同的数字 ^ 的结果为0, 0与任何数 ^ 的为这个数, 并且 ^ 遵循交换律 例如: 1^2^1^2^3 = 1^1^2^2^3 = 0^3 = 3

func singleNumber(_ nums: [Int]) -> Int {
    var ans = 0
    for n in nums {
        ans ^= n
    }
    return ans
}