Given an array of integers, every element appears twice except for one. Find that single one.
假設一個數組中除了一個數只出現一遍外,其他的都出現兩遍,找出這個只出現一遍的數。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not any(nums):
return None
ret = nums[0]
for i in range(1,len(nums)):
ret ^= nums[i]
return ret
用異或運算(XOR),太騷氣了。
A^A=0
A^B^A=B