原题如下,不让用extra memory,那么哈希什么的就不要考虑了。
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?
在大神们的指导下,这个问题用java位运算就可以轻松解决。
如果某个数字出现三次,二进制格式下,三个数字的第0位相加%3==0,第1位相加%3==0,第......
所以把所有数字考虑成二进制格式,每一位相加,然后%3,结果就是只出现一次的数字了。
public class Solution {
public static int singleNumber(int[] A) {
int l = A.length;
int result = 0;
int[ ] B = new int[32];
for(int i = 0; i < 32; i ++){
B[i] = 0;
for(int j = 0; j < l; j ++){
if(((A[j] >> i) & 1) == 1){
B[i] += 1;
}
}
B[i] %= 3;
result |= B[i] << i ;
}
return result;
}
}