此题目对应于 LeetCode 136
题目要求:
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?
给一个数组,其中每个元素都出现了两次除了一个元素,要求找出那个元素。要求时间O(n),空间O(1)。
考虑使用异或操作 ^,对应二进制位相同为0,不同为1,由于异或操作满足如下
性质: a^0=0,a^b=b^a,a^b^a=a^a^b=0^b=b
则对这个数组从头异或到尾就能得到那个只出现一次的元素,举例如下:
a^b^a^b^c=a^a^b^b^c=0^0^c=c
class Solution(object):
def singleNumber(self, nums):
tmp = 0
for i in nums:
tmp = tmp^i
return tmp