260. Single Number III

本文介绍了一种线性时间复杂度和常数空间复杂度的方法来找出数组中仅出现一次的两个元素。通过使用异或运算,文章详细解释了如何将问题转化为求解两个2*n+1形式的问题,并给出了具体的Java实现。

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

思路:

原本只有一个single number时是2*n+1的格局,现在变成了2*n+2的格局,所以只要想办法把他分解成两个2*n+1就可以了

所有的数字异或之后得到的结果是两个single number的异或xor(例如:3^5 0110),然后这个结果取补码得到-xor(例如:- 3^5 1010)

这两个结果取与得到xor从低位到高位,第一个非0数字的位置(例如lowbit = xor & -xor = 0010 & 0011 = 0010 3和5在二进制中第二位开始不同)

然后根据这个结果lowbit来区分数组中的数,由于异或的属性“同0异1”,所以这两个single number和lowbit的与的结果一定不同


public int[] singleNumber(int[] nums) {
	int xor = nums[0];
	int res[] = new int[2];
       for (int i = 1; i < nums.length; i++) {
		xor ^= nums[i];
	}
	int lowbit = xor & -xor;
	res[0] = 0;
	res[1] = 0;
	for (int i = 0; i < nums.length; i++) {
		if ((lowbit & nums[i]) != 0) {
			res[0] ^= nums[i];
		} else {
			res[1] ^= nums[i];
		}
	}
	return res;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值