from typing import List
# 数学法# 假设 nums = [a, a, a, b, b, b, c]# 结果为 3 * (a + b + c) - (a + a +a + b + b +b + c) = 2cclassSolution:defsingleNumber(self, nums: List[int])->int:return(3*(sum(set(nums)))-sum(nums))//2if __name__ =="__main__":
s = Solution()
a = s.singleNumber([2,2,1])print(a)
2.2 解法2 (复杂)
classSolution:defsingleNumber(self, nums: List[int])->int:
counts =[0]*32for n in nums:for j inrange(32):
counts[j]+= n &1
n >>=1# 进行右移
res, m =0,3# m表示 3的次数# 对每一位上的1个数取余for i inrange(32):
res <<=1
res |= counts[31- i]% m
return res if counts[31]% m ==0else~(res ^0xffffffff)
2.3 解法3 (位方法)
from typing import List
classSolution:defsingleNumber(self, nums: List[int])->int:
one, two =0,0for n in nums:
one ^= n
two |=(one & n)
three =(one & two)# 如果相应的位出现3次,则将改为重置位0
two &=~three
one &=~three
return one
if __name__ =="__main__":
s = Solution()
a = s.singleNumber([2,2,1])print(a)