题解 | #数组中只出现一次的两个数字#
数组中只出现一次的两个数字
http://www.nowcoder.com/practice/389fc1c3d3be4479a154f63f495abff8
//创建一个HashMap,将数字出现的次数保存至map中
//再对map进行迭代遍历
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 *.代码思路 * 利用HashMap存储数组中每个数字及出现的次数, *.再通过遍历数组和HashMap查找出出现次数为1的两个数。 * @param array int整型一维数组 * @return int整型一维数组 */ public int[] FindNumsAppearOnce (int[] array) { /** num为长度为2的数组,传出参数 将num[0],num[1]设置为返回结果 */ int[] num = new int[2]; //利用HashMap存储数组中每个数字及出现的次数 HashMap<Integer,Integer> map = new HashMap<>(); //将数组中的值和出现次数保存到HashMap中 for(int i=0; i<array.length; i++) { if(map.containsKey(array[i])) map.put(array[i],2); else map.put(array[i],1); } //设置标志,如果出现遍历次数为1的数,就将其设为true boolean flag = false; //对map进行迭代遍历 Set<Map.Entry<Integer, Integer>> entires = map.entrySet(); Iterator<Map.Entry<Integer, Integer>> iterator = entires.iterator(); while(iterator.hasNext()) { Map.Entry<Integer, Integer> next = iterator.next(); if(next.getValue() == 1)//如果当前数字出现的次数为1 { if(flag == false) { //如果之前没有出现过次数为1的数 num[0] = next.getKey(); flag = true; } else num[1] = next.getKey(); } } return num; } }