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]
is also correct. - Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
思路:如果按照以前的做法,每个数都对结果来做异或运算的话,会将两个数混在一起,怎么区分呢?
想了很久都没想到解决方案,看了网上的解答才有眉目:找到最后结果的第一个不为0的二进制位,可以将两个数区分开来,
然后对每个数再次进行异或运算(与刚才获得的结果),不同的是,如果此数的上述二进制为1,则对res[0]做,如果为0,对res[1]做;
如此,所有数被分成两拨,经过异或运算后就能找到这两个数。
非常巧妙。
c++实现:
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int temp=0;
for (int i=0;i<nums.size();i++)
temp^=nums[i];
int dif=temp&(~(temp-1)); //get the last digit of 1
vector<int> res;
res.push_back(0);
res.push_back(0);
for (int i=0;i<nums.size();i++){
if (dif&nums[i])
res[0]^=nums[i];
else
res[1]^=nums[i];
}
return res;
}
};