數組中除一個數出現一次外,其餘均出現兩次。找出該數。要求 O(n) 時間,O(1) 空間。
x ^ x = 0x ^ 0 = x因此所有數異或後,成對數抵消為 0,剩下的即為單獨數。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for (int x : nums) res ^= x;
return res;
}
};
逐位統計模 3:bits[i] = (bits[i] + (x>>i&1)) % 3,重構結果。或用有限狀態機兩個變量 ones, twos 追蹤出現 1/2 次的位模式。