給定一個非空整數數組,除了某個元素只出現一次以外,其余每個元素均出現兩次。找出那個只出現了一次的元素。
說明:
你的算法應該具有線性時間復雜度。 你可以不使用額外空間來實現嗎?
示例 1:
輸入: [2,2,1]
輸出: 1
示例 2:
輸入: [4,1,2,1,2]
輸出: 4
思路
很容易想到的2個方法是:
- 用list.count()方法統計只出現一次的個數,很不幸的是,這個超時了
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
X = [i for i in nums if nums.count(i) == 1]
return x[0]
- 用collections.Counter(),會返回一個字典,key為元素,value為元素出現的次數,只要找到value小於2的就好了,雖然沒有超時,但是效率也不夠讓人滿意,才超越了10%左右
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
x = collections.Counter(nums)
for key,value in x.items():
if value < 2:
return key
改進的版本
提交后看了最快的代碼,思路是運用按位異或運算符,當兩對應的二進位相異結果為1,真值表如下:
| a | b | c |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
可以看出如果有兩個元素是相等的,按位異或的結果會是0,而0與任何數都等於這個數本身(也就是保存了這個數)
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
for num in nums:
result = result ^ num
return result
