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?
1.先异或,得到的值是两个只出现一次的整数的异或值。
2.找出该异或值中第一个不为0的位置,即两个整数不相等的位。
3.根据该位将整数划分为两部分,两个整数分别位于两个部分。异或即可分别得到两个整数。
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int xres = nums[0];
for (int i = 1; i < nums.size(); i++){
xres ^= nums[i];
}
int iOne = 0;
for (int i = 0; i < 32; i++){
if ((xres >> i) & 1){
iOne = i;
break;
}
}
int res1 = 0, res2 = 0;
for (int i = 0; i < nums.size(); i++){
if ((nums[i] >> iOne) & 1){
res1 ^= nums[i];
}
else{
res2 ^= nums[i];
}
}
vector<int> res;
res.push_back(res1);
res.push_back(res2);
return res;
}
};