Map中put和putIfAbsent的区别

力扣277周赛第三题

5990,找出数组中所有孤独数字

    public List<Integer> findLonely(int[] nums) {
        List<Integer> ans = new LinkedList<>();
        HashMap<Integer,Integer> h = new HashMap<>();
        for(int x : nums){
            h.putIfAbsent(x,0);//x做key,value是x的出现次数
            h.put(x,h.get(x) + 1);
        }
        for(int x : h.keySet()){
            if(h.get(x) == 1 && !h.containsKey(x - 1) && !h.containsKey(x + 1)){
                ans.add(x);
            }
        }
        return ans;
    }
}

参考来源,put和putIfAbsent的区别

put在放入数据时,如果放入数据的key已经存在与Map中,最后放入的数据会覆盖之前存在的数据, 而putIfAbsent在放入数据时,如果存在重复的key,那么putIfAbsent不会放入值。

全部评论

相关推荐

axiom15:校友,我感觉你这个简历去华子暑期实习随便去了
点赞 评论 收藏
分享
喵_coding:年底缺人是短视频营造出来的 而且一般说的也很宽泛 不是特指后端
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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