[leetcode][ビット演算]Single Number III
1437 ワード
タイトル:
Given an array of numbers
For example:
Given
Note: The order of the result is not important. So in the above example, Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
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:
[5, 3]
is also correct. class Solution {
public:
int single(vector &nums){
if (nums.empty()) return -1;
int res = nums[0];
for (int i = 1; i < nums.size(); ++i) res ^= nums[i];
return res;
}
vector singleNumber(vector& nums) {
vector 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 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;
}
};