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:使用亦或操作,最后剩下的一定是单独的那个
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res=0;
for(auto n:nums)
{
res^=n;
}
return res;
}
};方法2:使用set,如果已经存在,就删除,不存在就添加,那么剩下的那个元素就是单个的那个数
class Solution {
public:
int singleNumber(vector<int>& nums) {
set<int> res;
for(auto n:nums)
{
if(res.find(n)!=res.end()) res.erase(n);
else res.insert(n);
}
return *res.begin();
}
};