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长度的数组存放所有位置上出现一的数量,再除以K取余
class Solution {
public:
int singleNumber(vector<int>& nums) {
vector<int> record(32,0);
for (int i = 0; i < nums.size(); i++){
int n = 1;
for (int j = 0; j < 32; j++){
record[j] += (n&nums[i]);
n = n << 1;
}
}
int res=0;
for (int i = 0; i < 32; i++){
record[i] = record[i] % 3;
if (record[i])
res = res + pow(2,i);
}
return res;
}
};