Link

Medium Bit Manipulation

Amazon

2020-05-30

260. Single Number III

Similar Question: LeetCode Question 136, LeetCode Question 137

Question:

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 1:

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:

The xor for all the number is actually a xor b. Thus, we can use the last digit x & ~(x-1) to seperate the number into two parts.

class Solution {
    public int[] singleNumber(int[] nums) {
        int sum = 0;
        int[] result = new int[2];
        
        for (int i : nums) {
            sum ^= i;
        }
        
        sum = sum & (~ sum + 1);
        for (int i : nums) {
            if ((sum & i) == 0 ) {
                result[0] ^= i;
            } else {
                result[1] ^= i;
            }
        }
        
        return result;
    }
}