Leetcode

Single Number III

  • Time:O(n)
  • Space:O(1)

C++

class Solution {
 public:
  vector<int> singleNumber(vector<int>& nums) {
    const int xors = accumulate(begin(nums), end(nums), 0, bit_xor<>());
    const int lowbit = xors & -xors;
    vector<int> ans(2);

    // seperate nums into two groups by the lowbit
    for (const int num : nums)
      if (num & lowbit)
        ans[0] ^= num;
      else
        ans[1] ^= num;

    return ans;
  }
};

JAVA

class Solution {
  public int[] singleNumber(int[] nums) {
    final int xors = Arrays.stream(nums).reduce((a, b) -> a ^ b).getAsInt();
    final int lowbit = xors & -xors;
    int[] ans = new int[2];

    // seperate nums into two groups by the lowbit
    for (final int num : nums)
      if ((num & lowbit) > 0)
        ans[0] ^= num;
      else
        ans[1] ^= num;

    return ans;
  }
}

Python

class Solution:
  def singleNumber(self, nums: List[int]) -> List[int]:
    xors = reduce(operator.xor, nums)
    lowbit = xors & -xors
    ans = [0, 0]

    # seperate nums into two groups by the lowbit
    for num in nums:
      if num & lowbit:
        ans[0] ^= num
      else:
        ans[1] ^= num

    return ans