LeetCode 137. Single Number II

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int singleNumber(vector<int>& nums) {
unordered_map<int, int> freq;
for (const auto& num: nums)
++freq[num];
int ans = 0;
for (auto [num, occ]: freq)
if (occ == 1) {
ans = num;
break;
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = 0;
for (int i = 0; i < 32; ++i) {
int sum = 0;
for (const auto& num : nums) {
sum += (num >> i) & 1;
}
if (sum % 3)
ans |= (1 << i);
}
return ans;
}
};