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?
比较经典的老问题,所有数字异或,找到最后一位不同的,根据它来分组。
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int pivot = 0;
for (int i = 0; i < nums.size(); ++i) {
pivot ^= nums[i];
}
pivot ^= pivot & (pivot - 1);
int n1 = 0, n2 = 0;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] & pivot) {
n1 ^= nums[i];
}
else {
n2 ^= nums[i];
}
}
vector<int> result;
result.push_back(n1);
result.push_back(n2);
return result;
}
};