# 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.

Example:

Input:  [1,2,1,3,2,5]
Output: [3,5]

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

# Solution

Approach 1: Hash map.

Approach 2: Bit manipulation.

# Code (Python)

Approach 1:

Approach 2:

# Code (C++)

Approach 1:

// Hash talbe.
class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        vector<int> res;
        unordered_map<int,int> umap;
        for (int i = 0; i < nums.size(); ++i)
        {
            umap[nums[i]]++;
        }
        for (unordered_map<int,int>::iterator iter = umap.begin();
            iter != umap.end(); ++iter)
        {
            if (iter->second == 1)
                res.push_back(iter->first);
        }
        return res;
    }
};

Approach 2:

// Let's say the two numbers are a and b. Xor of all numbers will be a^b.
// (a^b) & -(a^b) will leave only the last bit that is 1 (which is different in a and b).
// Then do another round of xor based on (a^b) & -(a^b) to find out a and b respectively.
class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        int tmp = 0;
        for (int i = 0; i < nums.size(); ++i)
        {
            tmp ^= nums[i];
        }
        tmp = tmp & -tmp;
        vector<int> res = vector(2, 0);
        for (int i = 0; i < nums.size(); ++i)
        {
            if (nums[i] & tmp)
                res[0] ^= nums[i];
            else
                res[1] ^= nums[i];
        }
        return res;
    }
};