package com.wsy.sword;
public class FindNumsAppearOnce {
/*
* 一个整型数组里除了两个数字之外,其他的数字都出现了两次。
* 请写程序找出这两个只出现一次的数字
*
* 思路:
* 1. 可以用位运算实现,如果将所有所有数字相异或,则最后的结果肯定是那两个只出现一次的数字异或
* 2. 根据异或的结果1所在的最低位,把数字分成两半,每一半里都还有只出现一次的数据和成对出现的数据
* 3. 这样继续对每一半相异或则可以分别求出两个只出现一次的数字
*/
public void findNumsAppearOnce(int [] array,int num1[] , int num2[]) {
if(array == null || array.length < 2) {
return;
}
int temp = 0; //得出两个只出现一次数字的异或值temp
for (int i : array) {
temp ^= i;
}
//找出此异或值第一个为1的最低位
int index = 0;
while((temp & 1) == 0) {
index++;
temp = temp >> 1;
}
//这样继续对每一半相异或则可以分别求出两个只出现一次的数字
for (int i : array) {
if((isBit(i, index) != 0)) {
num1[0]^=i;
}else {
num2[0]^=i;
}
}
}
private int isBit(int num, int index) {
num = num >> index;
return (num&1);
}
public static void main(String[] args) {
int[] array = {1,2,1,3,2,5};
FindNumsAppearOnce find = new FindNumsAppearOnce();
int[] num1 = new int[1];
int[] num2 = new int[1];
find.findNumsAppearOnce(array, num1, num2);
System.out.println(num1[0]);
System.out.println(num2[0]);
}
}
数组中只出现一次的数字
最新推荐文章于 2022-04-21 18:09:17 发布