题目
1. 常规统计
class Solution {
public:
int singleNumber(vector<int>& nums) {
for(int i = 0; i <= nums.size(); ++i)
if(count(nums.begin(), nums.end(), nums[i]) == 1) // count函数统计数字出现次数
return nums[i];
return 0;
}
};
2. 位运算
- 任何数和0做异或运算,结果仍然是原来的数,即 a ⊕ 0 = a a \oplus 0=a a⊕0=a。
- 任何数和其自身做异或运算,结果是0,即 a ⊕ a = 0 a \oplus a=0 a⊕a=0。
- 异或运算满足交换律和结合律,即 a ⊕ b ⊕ a = b ⊕ a ⊕ a = b ⊕ ( a ⊕ a ) = b ⊕ 0 = b a \oplus b \oplus a=b \oplus a \oplus a=b \oplus (a \oplus a)=b \oplus0=b a⊕b⊕a=b⊕a⊕a=b⊕(a⊕a)=b⊕0=b。
由本题可以发现,只有一个数只出现一次,其余数都出现两次,因此将所有数进行位运算即可。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = 0;
for (int i: nums) // 基于范围的循环
ans ^= i;
return ans;
}
};