LeetCode(260) Single Number III


タイトル
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?
ぶんせき
1つの無秩序配列を与え、1回しか現れない2つの要素を含み、残りの要素は2回現れ、この2つの要素を見つけます.
要求、線形時間、定数空間.
ACソース
class Solution {
public:
    //   :      unordered_set,     O(n)   
    vector<int> singleNumber1(vector<int>& nums) {
        if (nums.empty())
            return vector<int>();

        int len = nums.size();

        unordered_set<int> us;
        for (int i = 0; i < len; ++i)
        {
            if (us.count(nums[i]) == 0)
                us.insert(nums[i]);
            else
                us.erase(nums[i]);
        }//for

        return vector<int>(us.begin(), us.end());
    }

    //   :       ,       
    vector<int> singleNumber(vector<int>& nums) {
        if (nums.empty())
            return vector<int>();

        int len = nums.size();
        int res = 0;
        for (int i = 0; i < len; ++i)
        {
            res ^= nums[i];
        }//for

        vector<int> ret(2, 0);
        //     ,        ,                ,        
        int n = res & (~(res - 1));
        for (int i = 0; i < len; ++i)
        {
            if ((n & nums[i]) != 0)
            {
                ret[0] ^= nums[i];
            }
            else{
                ret[1] ^= nums[i];
            }//else
        }//for

        return ret;
    }
};

GitHubテストプログラムソースコード