Leet Code的一道, 谁能帮我解释一下 for 循环中 每句代码的意思?
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?
方法 2:用 ones 记录到当前处理的元素为止,二进制 1 出现“1 次”(mod 3 之后的 1)的有哪些二进制位;
用 twos 记录到当前计算的变量为止,二进制 1 出现“2 次”(mod 3 之后的 2)的有哪些二进制位。
当 ones 和 twos 中的某一位同时为 1 时表示该二进制位上 1 出现了 3 次,此时需要清零。
即用二进制模拟三进制运算。最终 ones 记录的是最终结果。
int singleNumber(int A[], int n) {
int ones = 0, twos = 0, threes = 0;
for (int i = 0; i < n; ++i) {
twos |= (ones & A[i]);
ones ^= A[i];
threes = ~(ones & twos);
ones &= threes;
twos &= threes;
}
return ones;
}