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
重点: 两个相同元素 异或 == 0
这题的重点先把所有元素 ^ 求出两个出现一次元素的异或值,这里我们称为 re,re代表两个出现一次元素的位运算的不同值。比如 010 和 011 的异或值是 001,表明右边第一位取值不同。这个时候我们把所有元素的右边第一位进行计算,如果是 1 则和 a(初始为0) 异或, 如果是 0 则和 b(初始为0) 异或。这样就成功把两个出现一次的元素分散到两个不同的地方异或了。又因为两个相同的元素异或 == 0, 所以 a和b就是所求值。
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};
}