Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2] Output: 3
Example 2:
Input: [0,1,0,1,0,1,99] Output: 99
思路:
两种方案,一种是该类问题的通用解决方案;一种是特殊优化版。
方案1
我们对int类型的每一个bit位进行记录,如果出现的次数是3的倍数说明应该被移除。
int singleNumber(vector<int>& nums) {
int res = 0;
vector<int> single(32, 0);
for (int i = 0; i < 32; i++){
for (int j = 0; j < nums.size(); j++){
if (nums[j] >> i & 1) single[i]++;
}
single[i] %= 3;
res |= single[i] << i;
}
return res;
}
方案2
该方案是对方案1的优化。
int singleNumber2(vector<int>& nums){
int ones = 0, twice = 0, thirds = 0;
for (int i = 0; i < nums.size(); i++){
twice |= ones & nums[i];
ones ^= nums[i];
thirds = ones & twice;
ones &= ~(ones&thirds);
twice &= ~(twice&thirds);
}
return ones;
}