题目描述
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
输入:[1,4,1,6]
输出:[4,6]
说明:返回的结果中较小的数排在前面
思路:(1)定义一个hashmap来存储存储所遍历的数组,如果该数字在hashmap中没有出现过,则将其添加进hashmap,如果出现过,就将其出现次数增加1.
(2)遍历hashmap,将其中的出现次数等于1的数字添加进新定义的数组当中,最后对数组进行排序.返回数组即可.
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型一维数组
* @return int整型一维数组
*/
public int[] FindNumsAppearOnce (int[] array) {
// write code here
int[] res = new int[2];
int index =-1;
Map<Integer,Integer> hashmap = new HashMap<>();
for(int i=0;i<array.length;i++){
if(!hashmap.keySet().contains(array[i])){
hashmap.put(array[i],1);
}else{
int value =hashmap.get(array[i])+1;
hashmap.put(array[i],value);
}
}
Iterator<Map.Entry<Integer,Integer>> entries = hashmap.entrySet().iterator();
while(entries.hasNext()){
Map.Entry<Integer,Integer> entry =entries.next();
if(entry.getValue()==1){
res[++index] =entry.getKey();
}
}
Arrays.sort(res);
return res;
}
}