题目

July 7, 2021 · View on GitHub

一个整型数组里除了两个数字之外,其他的数字都出现了两次。

请写程序找出这两个只出现一次的数字。

你可以假设这两个数字一定存在。

样例

输入:[1,2,3,3,4,4]

输出:[1,2]

参考答案

class Solution {
public:
    vector<int> findNumsAppearOnce(vector<int>& nums) {
        int sum = 0;
        for(auto x : nums) sum ^=x;
        int k = 0;
        while(!(sum>>k & 1))k++;
        int first = 0;
        for(auto x: nums)
            if(x>>k&1)
                first ^= x;
        return vector<int>{first,sum^first};
    }

};