Given an array of integers, every element appears twice except for one. Find that single one.
class Solution {
public:
int singleNumber(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(),nums.end());
if(n == 0)
return -1;
if(n == 1)
return nums[0];
int cnt = 1;
for(int i = 0; i < n; i++)
{
if(nums[i] == nums[i+1])
cnt = 0;
else
{
cnt++;
if(cnt>=2)
return nums[i];
}
}
return nums[n-1];
}
};
class Solution { // use XOR
public:
int singleNumber(vector<int>& nums) {
int n = nums.size();
if (n == 0)
{
return -1;
}
int result = nums[0];
for (int i = 1; i < nums.size(); i++)
{
result = result ^ nums[i];
}
return result;
}
};
第二种方法很神奇。
1001^1001 is 0000.
9,3,9. :
step 1: 1001^0011 = 1010
step 2: 1010^1001 = 0011