# LC 260. Single Number III 位运算解法

## 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.

Follow up: Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

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]

## Solution

public int[] singleNumber(int[] nums) {
if (nums.length <= 2) return nums;
int re = 0;
for (int i : nums)
re ^= i;
int i = 0;
while (((re >> i) & 1) != 1)
++i;
int a = 0, b = 0;
for (int n : nums) {
if (((n >> i) & 1) == 1)
a ^= n;
else
b ^= n;
}
return new int[]{a, b};
}

11-27 3321

06-20 2万+
07-31 1884
11-29 3638
10-11 3483
03-15 1万+
05-14 8567
06-12 3644
02-05 4054
07-13 3210
09-09 7508
11-03 4135