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个相同的数字操作后置零。
联想到数字电路中的module-3计数器,思路采用类似这种状态机的实现。
定义两位的(B1,B0)。
(0,0)复位状态。
(0,1)输入一次A[i]。
(1,0)输入两次A[i]。
(1,1)输入三次A[i]。此时执行复位操作。直接复位到(0,0)。
所以B0的值就是只出现一次的结果。
可以看出:B0=B0^A[i];
B1=B1|B0&A[i];(注意或)
class Solution {
public:
int singleNumber(int A[], int n) {
int b0 = 0,b1 = 0,reset = 0;
for(int i=0;i<n;++i){
b1|=b0&A[i];
b0=b0^A[i];
reset=b0&b1;
b0=reset^b0;
b1=reset^b1;
}
return b0;
}
};
实际上直接用Map是非常简单的:
class Solution {
public:
int singleNumber(int A[], int n) {
map<int,int> ret;
for(int i=0;i<n;i++){
ret[A[i]]++;
}
for(auto i=ret.begin();i!=ret.end();++i){
if(i->second!=3)
return i->first;
}
}
};