陣列中只有一個元素出現一次,其餘皆出現三次。找出該元素。要求線性時間、常數空間。
對每個 bit 位(0~31),統計所有數字該位為 1 的總次數。因三次出現的數字每 bit 貢獻 3 的倍數,對 3 取餘後即為目標數字該 bit 的值。
class Solution {
public:
int singleNumber(vector& nums) {
int result = 0;
for (int i = 0; i < 32; ++i) {
int sum = 0;
for (int n : nums) {
if (n & (1 << i)) sum++;
}
if (sum % 3) result |= (1 << i);
}
return result;
}
};
用兩個整數 ones, twos 追蹤每 bit 出現 1 次、2 次的狀態:
int singleNumber(vector& nums) { int ones = 0, twos = 0; for (int n : nums) { ones = (ones ^ n) & ~twos; twos = (twos ^ n) & ~ones; } return ones; }
狀態轉移:00 → 10 → 01 → 00(對應 0→1→2→3 次)。
O(32·n) = O(n) 或 O(n)(狀態機版)。O(1)。