數組中恰有兩個元素出現一次,其餘均出現兩次。找出這兩個元素。O(n) 時間、O(1) 空間。
xorAll = a ^ b (a,b 為兩個單一元素)。xorAll != 0,至少有一位為 1。xorAll 的最低位 1:bit = xorAll & (-xorAll) (或 xorAll & ~(xorAll-1))。該位上 a 和 b 必異(一 0 一 1)。public class Solution {
public int[] singleNumber(int[] nums) {
int xorAll = 0;
for (int n : nums) xorAll ^= n;
int bit = xorAll & (-xorAll); // 最低位 1
int a = 0, b = 0;
for (int n : nums) {
if ((n & bit) != 0) a ^= n;
else b ^= n;
}
return new int[]{a, b};
}
}
class Solution {
public:
vector singleNumber(vector& nums) {
int xorAll = 0;
for (int n : nums) xorAll ^= n;
int bit = xorAll & -xorAll;
int a = 0, b = 0;
for (int n : nums) {
if (n & bit) a ^= n;
else b ^= n;
}
return {a, b};
}
};
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
xor_all = reduce(xor, nums)
bit = xor_all & -xor_all
a = b = 0
for n in nums:
if n & bit: a ^= n
else: b ^= n
return [a, b]
Single Number 系列終極形態:利用異或性質 + 位分組,將「兩個單一元素」問題降維為兩個「一個單一元素」子問題。面試必會,代碼極短、邏輯優美。可延伸討論:若三個單一元素如何分組(需更多位)、有符號整數負數處理(同樣適用,補碼表示下位運算無差別)。