This problem can also be solved using Hash map and this idea is quite simple on implementation.
But how to do it in linear time and constant space?
First of all, we know that if we do XOR to all the elements, we can get a^b in which a,b are the numbers we want respectively. Now, need to analysis the result of a^b. If any bit is '1' means a and b are different on this bit. So, we can find this one bit and '&' with all other numbers to get those have the same bit and XOR them. Then we get the number, say a. a^b^a = b. Done.
vector<int> singleNumber(vector<int>& nums) {
int len=nums.size();
vector<int> res;
if(len<2) return res;
int first = 0;
for(int i=0;i<len;i++)
{
first=first^nums[i];
}
int diff = 1;
while((first&diff)!=diff)
{
diff=diff<<1;
}
int result=0;
for(int i=0;i<len;i++)
{
if((nums[i]&diff)==diff)
{
result=result^nums[i];
}
}
res.push_back(result);
res.push_back(first^result);
return res;
}
Two things are tricky here: the priority of '&' is somehow lower than != and ==, and diff<<1 won't change diff.