题目

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
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int singleNumber(vector<int>& nums) {
int len =nums.size();
int result =nums[0];
for(int i=1;i<len;i++)
{
result =result^nums[i];
}
return result;
}
};

解答

使用位运算, XOR异或.

XOR will return 1 only on two different bits. So if two numbers are the same, XOR will return 0. Finally only one number left.
A ^ A = 0 and A ^ B ^ A = B.