LeetCode | 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

由于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;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值