题目链接:只出现一次的数字 III - 力扣 (LeetCode)
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.
Example:
Input: [1,2,1,3,2,5]
Output: [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?
只有两个单身,其他都是成对。找两个单身元素a和b
a和b的二进制表示必有第k位不同
把所有数按第k位分成两组,两组的异或和分别为a和b
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int sum = 0;
for(auto x : nums) sum ^= x;
int k = 0;
while(!(sum >> k & 1)) k ++;
// 第k位是1
int s2 = 0, s3 = 0;
for(auto x : nums)
if(x >> k & 1)
s2 ^= x;
vector<int> res({s2, sum ^ s2});
return res;
}
};