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) {
sort(nums.begin(),nums.end());
unordered_map<int,int> mymap;
unordered_map<int,int>::iterator it;
for(auto num : nums){
mymap[num]++;
}
for(auto it=mymap.begin();it!=mymap.end();it++)
if(it->second==1)
return it->first;
}
};
最最最最好的解法是用位运算!!!
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res=0;
for(auto num : nums)
res^=num;
return res;
}
};
想到这个方法的人太聪明了了!!!