[leetcode]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次,所以32bit的每个位上来自同一个数字的1都重复了3次,可以用一个int[32]的数组记录每个位上1出现的次数,然后对3取模。
模仿了来自[水中的鱼]的代码:(http://fisherlei.blogspot.com/2013/11/leetcode-single-number-ii-solution.html)
int singleNumber(vector<int>& nums) {
vector<int> bit(32,0);
for(int i =0; i< nums.size(); ++i)
{
int a=1;
for(int j =0; j<32; ++j)
{
int rotated;
if((rotated = nums[i]>>j) == 0)
break;
bit[j] += rotated & a;
}
}
int result=0;
for(int i =0; i<32; ++i)
{
result += (bit[i]%3 <<i);
}
return result;
}
类似的思想还有更牛掰的写法:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ones = 0, twos = 0;
for(int i = 0; i < nums.size(); i++){
ones = (ones ^ nums[i]) & ~twos;
twos = (twos ^ nums[i]) & ~ones;
}
return ones;
}
};
int singleNumber(int A[], int n) {
int ones = 0, twos = 0, threes = 0;
for (int i = 0; i < n; i++) {
twos |= ones & A[i];
ones ^= A[i];
threes = ones & twos;
ones &= ~threes;
twos &= ~threes;
}
return ones;
}
ones 代表第ith 位只出现一次的掩码变量
twos 代表第ith 位只出现两次次的掩码变量
threes 代表第ith 位只出现三次的掩码变量