剑指offer 56 - Ⅱ.数组中数字出现的次数Ⅱ
问题:一个数组,其中只有一个数出现过1次,其他数都出现了3次,找出这个只出现一次的数字。
思路:出现过3次的数的和一定能整除以3不留余数
- 遍历每一个数,数的每一bit对应加入长度为32的数组的各个位置;
- 数组各个位置保存的数对3取余就是ans相应bit的值,ans不断左移,每次取余后的数放入ans的最后位置;
- return ans;
class Solution {
public:
int singleNumber(vector<int>& nums) {
vector<int> sums(32,0);
for(int num:nums)
{
int i=31;
while(num != 0)
{
sums[i] += num & 1;
num >>= 1;
i--;
}
}
int res=0;
for(int i=0;i<32;i++)
{
res <<= 1; // res先左移
res |= sums[i]%3;
}
return res;
}
};
进阶:
- 有限状态自动机(待办)