题目
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字
法1:hash方法
import java.util.*;
//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
Map<Integer,Integer> hash=new HashMap<>();
for(int i=0;i<array.length;i++){
if(hash.get(array[i])==null){
hash.put(array[i],1);
}else{
hash.put(array[i],1+hash.get(array[i]));
}
}
int count=0;//记录是前面有几次出现了目标内容
for(int i=0; i < array.length; i++){
if(hash.get(array[i]) == 1){
if(count == 0){
num1[0] = array[i];
count++;
}else
num2[0] = array[i];
}
}
/*
Iterator it = hash.entrySet().iterator();
while(it.hasNext()){
int key=(int)it.next();
if(hash.get(key)==1){
if(num1[0]==0)
num1[0]=hash.get(key);
else{
num2[0]=hash.get(key);
}
}
}
*/
}
}
法2:位运算
前提知识:
异或运算:如果a、b两个值不相同,则异或结果为1。如果a、b两个值相同,异或结果为0。
n^0 = n;
n^n = 0;
n^n^m = n^(n^m) 满***换律
所以,我们可以让数组中的每一个数异或一下,最后会得到一个结果ret,就是两个出现一次的数字的异或结果这个结果肯定是由两个不同数字异或而来,因此我们找ret二进制中为1的位置i,因为1一定是由0,1异或而来,因此要求得两个数中,一定有一个数的二进制中的第i个位置为1, 一个为0.
如何找到位置i?可用i = ret ^ (-ret)
因为计算机用补码存取二进制数,而负数的补码为反码+1,举个例子
假如ret = 1110 , -ret = 0010 , 所以 i = 0010
所以,再异或一遍即可得到答案。