题目:一个整型数组里除了两个数字只出现一次,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
说明:返回的结果中较小的数排在前面
package case40_NumbersAppearOnce;
import java.util.*;
public class Solution {
/**
* 需求:在一个整型数组中,除了某两个数字之外,其他的数字都出现了两次。
* 请写程序找出这两个数字。要求时间复杂度为O(n),空间复杂度为O(1)
* 思路:
* 前提知识:
* 1,任何一个数字与其自身做 异或运算,结果都是0。
* 2,任何数字和 0 做异或运算都是数字本身。
* 解题方法:
* 若数组中只有1个数字不相同呢?
* 1,遍历数组,从头到尾依次异或,异或得到的结果就是那个不相同的数字。
* 若数组中有2个数字不相同呢?
* 1,遍历数组,从头到尾依次异或,异或得到的结果是要找的2个不同的数字的异或结果。
* 2,根据异或结果将两个数字分配到两个子数组中,其他数字也分别分配到这两个子数组中,
* 然后再分别异或。
* 3,因为2个相同的数字会分配到同一个子数组中去,所以这两个数字异或的结果为0,不会影响结果。
* 4,得到的结果
*
* @param array int整型一维数组
* @return int整型一维数组
*/
public int[] findNumsAppearOnce (int[] array) {
// write code here
if (null == array || array.length <= 1){
return null;
}
int or = 0;
int len = array.length;
for (int i = 0; i < len; i++) {
or ^= array[i];
}
int cur = 1;
while ((cur & or ) == 0){
cur <<= 1;
}
int num1 = 0;
int num2 = 0;
for (int i = 0; i < len; i++) {
int num = array[i];
if((cur & num) == 0){
num1 ^= num;
}else{
num2 ^= num;
}
}
return num1<num2? new int[]{num1, num2} : new int[] {num2, num1};
}
}
}