Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
分析
用一个长度为32的数组存贮每位中1出现的次数,由于除去要选择的那个数,其它的数都是出现三次,所以取完次数后%3,所得的结果就是唯一一个没有出现三次的那个数。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int count[32]={0};
int result=0;
for(int i=0;i<32;i++){
for(int j=0;j<nums.size();j++){
if((nums[j]>>i)&1){
count[i]++;
}
}
result |= (count[i]%3)<<i;
}
return result;
}
};