給定一個非空整數數組,除了某個元素只出現一次以外,其餘每個元素均出現兩次。找出那個只出現了一次的元素。
說明:
你的算法應該具有線性時間複雜度。 你可以不使用額外空間來實現嗎?
示例 1:
輸入: [2,2,1] 輸出: 1
示例 2:
輸入: [4,1,2,1,2] 輸出: 4
解題思路:
我用的是Python的字典,key爲數組裏的數字,value是數字的出現次數,當重複出現時,次數加1。最後循環字典,找出value爲1的就可以了。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = {}
number = 0
for i in nums:
if i in result:
result[i] += 1
else:
result[i] = 1
for i in result:
if result[i] == 1:
number = i
break
return number