Given An array of numbers nums, in which exactly, elements appear only once and all the other elements appear exactly t Wice. Find the 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. The above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could implement it using only constant space complexity? Problem-solving ideas: There is an array, where only two numbers appear once, the other numbers appear two times, to find out the two numbers. Refer to Signal number's second solution: http://blog.csdn.net/sinat_24520925/article/details/45576735 we divide this array into two arrays, Only one element appears at a time in each array. That is, the first XOR or all elements, get resultexclusive, find the binary representation of the resultexclusive in the right-to-left first bit 1, it indicates that there is one occurrence in the array of the value of the bit is different, a 0, The other is 0. The following is a good thing to do, the array of the bit is 0 of the XOR, all 1 of the XOR can be obtained only one occurrence of the two number. The code is as follows:
Class Solution {public
:
vector<int> singlenumber (vector<int>& nums) {
vector<int > res;
if (Nums.size () ==0) return res;
Res.push_back (0);
Res.push_back (0);
int resultexclusive=0;
for (int i=0;i<nums.size (); i++)
resultexclusive^=nums[i];
int indexof1=0;
while (((resultexclusive&1) ==0) && (indexof1<8*sizeof (int)))
{
resultexclusive= resultexclusive>>1;
++indexof1;
}
for (int i=0;i<nums.size (); i++)
{
if ((NUMS[I]>>INDEXOF1) &1==1)
res[0]^=nums[i];
else
res[1]^=nums[i];
}
return res;
}
};
It is worth noting that:
(resultexclusive&1) ==0)
(resultexclusive&1) must be added (), otherwise because the priority of = = is higher than &, it will cause the while loop cannot enter ....