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?
用one, two, three标记当前数出现一次、两次、三次。每处理一个数时分别计算与、异或、非,当前数字出现三个时前两个变量为1, 第3个变量为0;从而清除该数字;最后保留下来的one就是出现了一次的数字。
class Solution {
public:
int singleNumber(int A[], int n) {
int one = 0, two = 0, three = 0;
for(int i = 0; i < n; ++i) {
two |= one & A[i];
one ^= A[i];
three = ~(one & two);
one &= three;
two &= three;
}
return one;
}
};