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?
分析:考察位运算。
运用三个整型变量,把他们看做二进制数,用这三个数模拟三进制运算。
ones 每一位存放1(余3)出现一次的情况;
twos 每一位存放1(余3)出现两次的情况;
当ones和twos某一位都是1的时候,说明该位1出现了三次,这时候要把ones和twos相应位置清0,清0的具体做法就是将ones和twos按位求交再取反,之后分别与ones和twos按位求交即可。
这样,最后ones就是结果。
public class Solution {
public int singleNumber(int[] A) {
int ones = 0, twos=0, temp = 0;
for(int i=0; i<A.length; i++){
twos = twos | (ones & A[i]);
ones = ones^A[i];
temp = ~(ones & twos);
ones = ones & temp;
twos = twos & temp;
}
return ones;
}
}