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?
算法分析: a⊕b⊕a=b ,每个都去异或,那么最后得到的数就是那个孤立的数。
C语言版
int singleNumber(int* nums, int numsSize) {
int i, n = nums[0];
for(i = 1; i < numsSize; i++)
n ^= nums[i];
return n;
}
Python版
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = nums[0]
for t in nums[1:]:
n ^= t
return n