题目:
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:
int single(vector<int> &nums){
if (nums.empty()) return -1;
int res = nums[0];
for (int i = 1; i < nums.size(); ++i) res ^= nums[i];
return res;
}
vector<int> singleNumber(vector<int>& nums) {
vector<int> res;
if (nums.empty()) return res;
int xxor = nums[0];
for (int i = 1; i < nums.size(); ++i){
xxor ^= nums[i];
}
//xxor为x1和x2的异或结果(因为x1和x2不相等,所以xxor一定不为0,也就是说xxor至少有1位为1),其中为1的位表示两者在该位不同,利用该位将nums分成两组,每组中的数的特点是:只有一个数只出现了一次,其他数都出现了两次
int mask = 1;
while ((mask & xxor) == 0) mask <<= 1;
vector<int> nums0, nums1;
for (int i = 0; i < nums.size(); ++i){
if ((mask & nums[i]) == 0) nums0.push_back(nums[i]);
else nums1.push_back(nums[i]);
}
int x1 = single(nums0);
int x2 = single(nums1);
res.push_back(x1);
res.push_back(x2);
return res;
}
};