题目:
Given an 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?
思路:
这还是一道考查位操作的题目。由于除了某个数之外,其余所有数都严格出现三次,对于所有出现三次的数,我们只要把它各个位上的数加起来,然后模3,最终结果必然为0。而某个数如果只出现一次,这种处理的结果仍然是该数本身。所以思路就清楚了,见下面的代码。时间复杂度O(n),空间复杂度为O(1)。
代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int bits[32] = {0};
int result = 0;
for(int i = 0; i < 32; i++) {
for(int j = 0; j < nums.size(); j++) {
bits[i] += (nums[j] >> i) & 1;
}
result |= (bits[i] % 3) << i;
}
return result;
}
};