# 260. Single Number III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:

1. The order of the result is not important. So in the above example, [5, 3] is also correct.
2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

1.我的答案

class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
map<int,int> mp;
vector<int> res;
int len = nums.size();
for(int i = 0; i < len; i++){
if(mp.find(nums[i]) == mp.end()){
mp[nums[i]] = 1;
}
else
mp[nums[i]]++;
}
for(auto iter = mp.begin(); iter != mp.end(); iter++){
if(iter->second == 1)
res.push_back(iter->first);
}
return res;
}
};

2.看了别人答案做的

int bit = a & ~(a-1);

bit即可得到a中右边第一次出现1的数。

class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int temp = 0;
for(int i = 0; i < nums.size(); i++){
temp ^= nums[i];
}
int xors = temp & ~(temp - 1);
int num1 = 0, num2 = 0;
for(int j = 0; j < nums.size(); j++){
if((nums[j] & xors) > 0)
num1 ^= nums[j];
else
num2 ^= nums[j];
}
vector<int> res;
res.push_back(num1);
res.push_back(num2);
return res;
}
};

08-17 1617

07-30 1107

09-13 9473

12-02 1154

02-18 4943

08-30 121

11-15 1994

02-13 108

05-24 125

07-20 276