链接:
题目:
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
我的解法:xor,全部异或一遍,剩下的结果就是出现一次的数字
class Solution(object):
def singleNumber(self, nums):
result = 0
for num in nums:
result ^= num
return result
xor 相异为1
a ^ a = 0
a ^ 0 = a
a ^ b ^ a = b
解法2:
def singleNumber(self, nums):
return 2*sum(set(nums))-sum(nums)
解法三: dict
def singleNumber(self, nums):
dic = {}
for num in nums:
dic[num] = dic.get(num, 0)+1
for key, val in dic.items():
if val == 1:
return key
python dict 函数: