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?
class Solution {
public:
int singleNumber(vector<int>& nums) {
set<int> hash;
for(int i=0;i<nums.size();i++)
{
if(hash.find(nums[i])!=hash.end())
hash.erase(nums[i]);
else
hash.insert(nums[i]);
}
return *hash.begin();
}
};
这是使用set来实现的;
使用bit操作的代码如下:
nt singleNumber(int a[], int n) {
//xor all numbers, the left over number would be the non repeated one
// since the equl numbers cancel out each others bits
int num = 0;
for (int i = 0; i < n; ++i) {
num ^= a[i];
}
return num;
}
这个更高效。