數組中只有兩個數字出現一次,其餘均出現兩次。線性時間、常數空間找出這兩個數字。
public int[] singleNumber(int[] nums) {
int xorAll = 0;
for (int n : nums) xorAll ^= n;
int diffBit = xorAll & (-xorAll); // 取最低位 1
int a = 0, b = 0;
for (int n : nums) {
if ((n & diffBit) != 0) a ^= n;
else b ^= n;
}
return new int[]{a, b};
}