Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

思路:

这里使用异或运算,异或运算有如下性质:

1.相同元素异或为0,0与任何数异或等于任何数,有a^b^a=b。

2.此外,异或还可以用于两个元素交换a=a^b^(b=a)。

实现:

1
2
3
4
5
def singleNumber(nums):
res = 0
for i in nums:
res = res^i
return res