https://leetcode.com/problems/single-number-iii/description/
vector<int> singleNumber(vector<int>& nums) {
vector<int> res;
int x = 0;
for(int n: nums) {
x ^= n;
}
int b = 1;
while((b&x) == 0) b <<= 1;
// explanation in link
// // Get the XOR of the two numbers we need to find
// int diff = accumulate(nums.begin(), nums.end(), 0, bit_xor<int>());
// // Get its last set bit, diff &= ~(diff-1) is slower
// diff &= -diff;
int y = 0, z = 0;
for(int n: nums) {
if(b&n) y ^= n;
else z ^= n;
}
return {y, z};
}
No comments:
Post a Comment