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?
// I. using extra memory
class Solution {
public:int singleNumber(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
map<int, int> table;
table.clear();
map<int, int>::iterator iter;
for (int i=0;i<n;++i){
iter = table.find(A[i]);
if (iter==table.end())
table[A[i]] = 1;
else
table[A[i]]++;
}
for (iter = table.begin();iter!=table.end();++iter){
if ((iter->second)%3==1)
return iter->first;
}
}
};
// without using extra space
class Solution {
public:int singleNumber(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int n0, n1, n2;
n1 = 0; n2 = 0;
for (int i=0;i<n;i++){
n0 = ~(n1|n2);
n2 = (n2 & ~A[i]) | (n1 & A[i]);
n1 = (n1 & ~A[i]) | (n0 & A[i]);
}
return n1;
}
};