您的位置:首页 > 其它

LeetCode | Single Number II

2014-02-14 23:44 399 查看
题目

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
由于int型由32bit表示,因此可以用一个长度为32的int数组保存各个比特位上1出现的次数。最后,将数组各元素对3取余,那么32位数组就纪录了只出现了一次的整数的二进制表示。

解法1

public class SingleNumberII {
private final static int INTEGER_DIGITS = 32;

public int singleNumber(int[] A) {
if (A == null || A.length <= 0) {
return 0;
}

int ret = 0;
int[] count = new int[INTEGER_DIGITS];
for (int i = 0; i < INTEGER_DIGITS; ++i) {
for (int j = 0; j < A.length; ++j) {
count[i] += (A[j] >> i) & 0x0001;
}
ret |= (count[i] % 3) << i;
}
return ret;
}
}
分析2

可以用三个整数纪录32个比特位上1出现的次数,ones中比特位为1,表示该位出现了1次,twos中比特位为1,表示该位出现了2次,当某比特位出现三次后,就将ones和twos中对应比特位置为0。遍历完一遍数组后,ones即表示只出现了一次的数字。

解法2

public class SingleNumberII {
public int singleNumber(int[] A) {
if (A == null || A.length <= 0) {
return 0;
}

int ones = 0, twos = 0, threes = 0;
for (int i = 0; i < A.length; ++i) {
twos |= ones & A[i];
ones ^= A[i];
threes = ones & twos;
ones &= ~threes;
twos &= ~threes;
}
return ones;
}
}分析3
同样是利用三个整数纪录32个比特位上1出现的次数,不过方法看上去更简洁些,具体参考http://oj.leetcode.com/discuss/857/constant-space-solution。

同时,上述链接中还将该问题扩展至了:数组中所有整数都出现了k次,除了一个数只出现了l次,如何找到这个数。

解法3
public class SingleNumberII {
public int singleNumber(int[] A) {
if (A == null)
return 0;
int x0 = ~0, x1 = 0, x2 = 0, t;
for (int i = 0; i < A.length; i++) {
t = x2;
x2 = (x1 & A[i]) | (x2 & ~A[i]);
x1 = (x0 & A[i]) | (x1 & ~A[i]);
x0 = (t & A[i]) | (x0 & ~A[i]);
}
return x1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode 二进制