Description
Given a non-empty 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?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
Solution: Bit Manipulation
我们可以把0对每个元素都XOR,这样所有出现两次的元素都会抵消,从而最后的结果就是唯一的那一个元素。
Proof:
XOR Property:
- a ^ 0 = a
- a ^ a = 0
- a ^ b = b ^ a
- (a ^ b) ^ c = a ^ (b ^ c)
交换位置,重复的元素一定可以被消除,而剩下的就是0 ^ 0 ^ 0 ^ 0 ^ … ^ single, 这样结果就是答案
//C++
//Time: O(n)
//Space: O(1)
int singleNumber(vector<int>& nums) {
int ans = 0;
for(int i = 0; i < nums.size(); ++i){
//XOR
ans ^= nums[i];
}
return ans;
}