Skip to content

Single Number III⚓︎

Link

Description⚓︎

Given an integer array 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. You can return the answer in any order.

You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.

Example 1:

  • Input: nums = [1,2,1,3,2,5]
  • Output: [3,5]
  • Explanation: [5, 3] is also a valid answer.

Example 2:

  • Input: nums = [-1,0]
  • Output: [-1,0]

Example 3:

  • Input: nums = [0,1]
  • Output: [1,0]

Constraints:

  • 2 <= nums.length <= 3 * 10^4
  • -2^31 <= nums[i] <= 2^31 - 1
  • Each integer in nums will appear twice, only two integers will appear once.

Solution⚓︎

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        int s = 0;
        for (auto num : nums) s ^= num;

        int k = 0;
        while (!(s >> k & 1)) k++;

        int n1 = 0;
        for (auto num : nums) {
            if (num >> k & 1) n1 ^= num;
        }

        // If s == a ^ b, n1 == a, then s ^ n1 == a ^ b ^ a == b
        return vector<int>({n1, s ^ n1});
    }
};

Another way of writing:

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        int xorAll = 0;
        for (int x : nums) xorAll ^= x;

        // int lowBit = xorAll & -xorAll;
        // avoid overflow
        int lowBit = ((xorAll == INT_MIN) ? xorAll : (xorAll & -xorAll));
        int xorB = 0;
        for (int x : nums) {
            if ((x & lowBit) == 0)
                xorB ^= x;
        }
        return {xorB, xorAll ^ xorB};
    }
};

Another way of writing:

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        unsigned int xorAll = 0;  // avoid overflow for test case: [1,1,0,-2147483648]
        for (int num : nums) xorAll ^= num;

        int lowBit = xorAll & -xorAll;
        vector<int> res(2);
        for (int num : nums) {
            res[(num & lowBit) != 0] ^= num;
        }
        return res;
    }
};

See reference (Chinese).