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?

Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Solution

public class Solution {
    public int[] singleNumber(int[] nums) {
        if (nums == null || nums.length == 0) return new int[0];

        int xor = nums[0];
        for (int i = 1; i < nums.length; i++) {
            xor ^= nums[i];
        }

        int i = 0;
        for (; i < 32; i++) {
            if ((xor >> i & 1) == 1) {
                break;
            }
        }

        int a = 1;
        int b = 1;
        for (int j = 0; j < nums.length; j++) {
            int current = nums[j];
            if ((current >> i & 1) == 1) {
                a ^= current;
            } else {
                b ^= current;
            }
        }

        a ^= 1;
        b ^= 1;

        int[] result = new int[2];
        result[0] = a;
        result[1] = b;
        return result;
    }
}

results matching ""

    No results matching ""