题目描述
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
思路: 采用异或,能找出一个数组中一个只出现一次的数字,题目中要求是两个。可以根据这种想法,把数组一分为二,左边的子数组异或得到一个数,右边的子数组 异或得到一个数,左右子树组的划分,首先把数组异或得到两个不同数的异或结果,找到他们最右边的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;
}
}