不需要额外空间的方法,就往位运算上想
136. 只出现一次的数字
异或运算的性质:
1.交换律:a ^ b ^ c <=> a ^ c ^ b
2.任何数于0异或为任何数 0 ^ n => n
3.相同的数异或为0: n ^ n => 0
a = [2,3,2,4,4]
2 ^ 3 ^ 2 ^ 4 ^ 4等价于 2 ^ 2 ^ 4 ^ 4 ^ 3 => 0 ^ 0 ^3 => 3
class Solution:
def singleNumber(self, nums: List[int]) -> int:
a = 0
for n in nums:
a ^= n
return a