137. Single Number II
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?
数组仅有一个数出现一次,其他的出现3次。找出那个出现一次的数。依然使用位运算来求解。
统计每一位上1出现的次数,1出现次数不为3的倍数的位所组成的数即为要找的数。
代码实现:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int n = nums.size();
int ones = ;
int twos = ;
int xthrees = ;
for(int i = ; i < n; ++i)
{
twos |= (ones & nums[i]);
ones ^= nums[i];
xthrees = ~(ones & twos);
ones &= xthrees;
twos &= xthrees;
}
return ones;
}
};