題目
給定一個(gè)非空整數(shù)數(shù)組,除了某個(gè)元素只出現(xiàn)一次以外,其余每個(gè)元素均出現(xiàn)兩次。找出那個(gè)只出現(xiàn)了一次的元素。
說(shuō)明:
你的算法應(yīng)該具有線性時(shí)間復(fù)雜度。 你可以不使用額外空間來(lái)實(shí)現(xiàn)嗎?
示例 1:
輸入: [2,2,1]
輸出: 1
示例 2:
輸入: [4,1,2,1,2]
輸出: 4
解題思路
class Solution:
def singleNumber(self, nums: [int]) -> int:
#列表方式
# tempList = []
# for i in nums:
# if i in tempList:
# tempList.remove(i)
# else:
# tempList.append(i)
# return tempList.pop()
#字典方式
# tempDic = {}
# for i in nums:
# if i in tempDic:
# del tempDic[i]
# else:
# tempDic[i] = 1
# return tempDic.popitem()[0]
#異或
ans = 0
for i in nums:
ans ^= i
return ans