首页 > 其他 > 详细

LeetCode | Single Number II

时间:2014-02-15 10:30:10      阅读:347      评论:0      收藏:0      [点我收藏+]

题目

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 | Single Number II

原文:http://blog.csdn.net/perfect8886/article/details/19215215

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!