
一、题目
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
二、思路
建一个hashMap,统计各数字出现的次数,然后遍历hashMap,输出出现一次的数字。
三、代码
//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果 import java.util.HashMap;
import java.util.Map;
import java.util.Set; public class Solution {
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) { if(array==null||array.length==0){
return;
} //新建hashMap,统计字数出现的次数
HashMap<Integer,Integer> hashMap=new HashMap<Integer, Integer>(); //存储字符出现一次的数
int[] num=new int[2];
//统计每个字符的次数
for(int key:array){
if(hashMap.containsKey(key)){
hashMap.put(key,hashMap.get(key)+1);
}else {
hashMap.put(key,1);
}
} //遍历,如果出现次数为1,则将改数保存到数组num中
int i=0;
Set<Map.Entry<Integer,Integer>> set=hashMap.entrySet();
for(Map.Entry<Integer,Integer> s:set){
if(s.getValue()==1){
num[i]=s.getKey();
i++;
}
} //保存结果
num1[0]=num[0];
num2[0]=num[1];
}
}
---------------------------------------------
参考链接:
https://www.nowcoder.com/practice/e02fdb54d7524710a7d664d082bb7811?tpId=13&tqId=11193&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking