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?
Solution in C++ 1:
class Solution {
public:
int singleNumber(vector<int>& nums) {
if(nums.size()==0) return 0;
int one=0, two=0, three=0;
for(int i=0; i<nums.size(); i++){
two |= one&nums[i];
one ^= nums[i];
three = one&two;
two &= ~three;
one &= ~three;
}
return one;
}
};
按比特求逻辑关系,注意2要放在1前面,否则会被1的新值影响。
Solution in C++ 2:
class Solution {
public:
int singleNumber(vector<int>& nums) {
if(nums.size()==0) return 0;
int solu[32]; //int值共有32位来储存
memset(solu, 0, sizeof(solu));
for(int i=0; i<nums.size(); i++){
for(int index=0; index<32; index++){
if ((nums[i]>>index)&1)
{
solu[index]++;
}
}
}
int result=0;
for(int i=0; i<32; i++){
result += (solu[i]%3<<i);
}
return result;
}
};
Note:
这里我们需要重新思考,计算机是怎么存储数字的。考虑全部用二进制表示,如果我们把 第 ith 个位置上所有数字的和对3取余,那么只会有两个结果 0 或 1 (根据题意,3个0或3个1相加余数都为0). 因此取余的结果就是那个 “Single Number”.
一个直接的实现就是用大小为 32的数组来记录所有 位上的和。