[leetcode] problem 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?

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public int[] singleNumber(int[] nums) {
int[] result = new int[2];
int xor = 0;
int num1 = 0;
int num2 = 0;

for (int num : nums)
xor ^= num;

int last = xor - (xor & (xor - 1));

for (int i = 0; i < nums.length; i++) {
if ((last & nums[i]) == 0)
num1 ^= nums[i];
else
num2 ^= nums[i];
}

result[0] = num1;
result[1] = num2;

return result;
}