题解 | #数组中只出现一次的两个数字#

数组中只出现一次的两个数字

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;
    }
}


全部评论

相关推荐

牛客刘北:如果暑期实习是27届的话,你要晚一年才会毕业,企业为什么会等你呢?要搞清时间逻辑呀!27届现在实习只能是在暑假实习,这是日常实习,不是暑期实习。所以多去投日常实习吧,暑期实习肯定不会要你的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务