給定整數陣列,除一個元素外其餘皆出現兩次。找出那個只出現一次的元素。要求線性時間、不使用額外空間。
a ^ a = 0a ^ 0 = a所有成對數字 XOR 後抵消為 0,剩下的即為單獨數字。
class Solution {
public:
int singleNumber(vector& nums) {
int result = 0;
for (int n : nums) result ^= n;
return result;
}
};
O(n),單次遍歷。O(1),僅一個整數變數。a^b,找一個為 1 的 bit 分組再各自 XOR。