暴力
class Solution {
public:
int singleNumber(vector<int>& nums) {
sort(nums.begin(),nums.end());
int i=0;
while(i<nums.size()){
if(i+2<nums.size()&&nums[i]==nums[i+1]&&nums[i]==nums[i+2])i+=3;
else break;
}
return nums[i];
}
};
哈希
class Solution {
public:
int singleNumber(vector<int>& nums) {
unordered_map<int,int>mp;
for(auto t:nums){
++mp[t];
}
for(auto [val,count]:mp){
if(count==1)return val;
}
return -1;
}
};
位运算
class Solution {
public:
int singleNumber(vector<int>& nums) {
vector<int>a(32,0);
for(auto t:nums){
for(int i=0;i<32;i++){
if((t>>i)&1==1)++a[i];
}
}
int ans=0;
for(int i=0;i<32;i++){
if(a[i]%3==1)ans+=1<<i;
}
return ans;
}
};