剑指offer 数组中只出现一次的数字

题目描述

一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。

思路: 采用异或,能找出一个数组中一个只出现一次的数字,题目中要求是两个。可以根据这种想法,把数组一分为二,左边的子数组异或得到一个数,右边的子数组 异或得到一个数,左右子树组的划分,首先把数组异或得到两个不同数的异或结果,找到他们最右边的1出现的位置,根据对应为为1,来划分数组。

public class Solution {
public void FindNumsAppearOnce(int[] array, int num1[], int num2[]) {
		if (array == null || array.length < 2)
			return;
		int bitResult = 0;
		for (int i = 0; i < array.length; i++)
			bitResult ^= array[i];
		int index = findFirstBitIs1(bitResult);
		for (int i = 0; i < array.length; i++)
			if (isBit1(array[i], index))
				num1[0] ^= array[i];
			else
				num2[0] ^= array[i];
	}

	// 判断target的右侧index位是否为1
	private boolean isBit1(int target, int index) {
		return ((target >> index) & 1) == 1;
	}

	// 查找num右侧第一个1的下标
	private int findFirstBitIs1(int num) {
		int indexBit = 0;
		// 注意判断位数合法性
		while ((num & 1) == 0 && indexBit < 32) {
			indexBit++;
			num >>= 1;
		}
		return indexBit;
	}
}    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值