题目描述:
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?
解题思路:
方法1:创建一个长度为sizeof(int)的数组count[sizeof(int)],count[i]表示在在i位
出现的1的次数。如果count[i]是3的整数倍,则忽略;否则就把该位取出来组成答案。
方法2:用one记录到当前处理的元素为止,二进制1出现“1次”(mod 3之后的1)的有哪
些二进制位;用two记录到当前计算的变量为止,二进制1出现“2次”(mod 3之后的2)的有哪
些二进制位。当one和two中的某一位同时为1时表示该二进制位上1出现了3次,此时需要清
零。即用二进制模拟三进制运算。最终one记录的是最终结果。
解题代码:
public int singleNumber(int[] A) {
int one=0;
int two=0;
int three=0;
for(int i=0;i<A.length;i++)
{
two|=one&A[i];
one^=A[i];
three=~(one&two);
two&=three;
one&=three;
}
return one;
}