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?
用 one 记录到当前处理的元素为止,二进制 1 出现“1 次”(mod 3 之后的 1)的有哪些二进制位;用 two 记录到当前计算的变量为止,二进制 1 出现“2 次”(mod 3 之后的 2)的有哪些二进制位。当 one 和 two 中的某一位同时为 1 时表示该二进制位上 1 出现了 3 次,此时需要清零。即用二进制模拟三进制运算。最终 one 记录的是最终结果。
class Solution {
public:
int singleNumber(int A[], int n) {
int ones = 0, twos = 0, threes = 0;
for( int i = 0; i < n; ++i){
threes = twos & A[i];
twos |= ones & A[i];
ones |= A[i];
twos = twos & ~threes;
ones = ones & ~threes;
}
return ones;
}
};