您的位置:首页 > 其它

[leetcode]Single Number II

2014-08-07 22:26 141 查看
Single Number II


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:用一个数组来模拟CPU位数,记录int类型的32位中每一位出现的次数,容易理解,可惜的是没有达到题中要求的O(1)空间。

public class Solution {
public int singleNumber(int[] a) {
int[] binary = new int[32];
for(int tem : a){
int bin = 1;
for(int i = 0; i < 32; i++){
if((tem & bin) == bin)
binary[i]++;
bin = bin << 1;
}
}
int res = 0;
for(int i = 0; i < 32; i++){
res |= (binary[i] % 3) << i;
}
return res;
}
}


思路2:对思路1的优化,对每一位进行数组的遍历,求出该位出现的次数,然后%3取模,对结果的该位进行赋值。

public class Solution {
public int singleNumber(int[] a) {
int res = 0;
for(int i = 0; i < 32; i++){
int binary = 1 << i;
int count  = 0;
for(int tem: a){
if((tem & binary) != 0){
count++;
}
}
res |= (count % 3) << i;
}
return res;
}
}


参考资料:http://www.cnblogs.com/jdflyfly/p/3828929.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: