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:
- The order of the result is not important. So in the above example,
[5, 3]
- Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
class Solution {
public:
//两个不同的数出现一次,其余两次,异或
vector<int> singleNumber(vector<int>& nums) {
int n,ans1,ans2;
ans1=0;
n=nums.size();
for(int i=0;i<n;i++){
ans1^=nums[i];
}
ans2=ans1;
int k=0;
while((ans2&1)==0)
{
ans2>>=1;
k++;
}
ans2=ans1;
for(int i=0;i<n;i++){
if( (nums[i]>>k)&1)
ans1^=nums[i];
}
ans2=ans1^ans2;
vector<int> res;
res.push_back(ans1);
res.push_back(ans2);
return res;
}
};









