您的位置:首页 > 编程语言 > Java开发

LeetCode OJ平台上Single Number II题目使用java位运算解决

2014-06-11 21:55 369 查看
原题如下,不让用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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: