力扣题目:独一无二的出现次数

    力扣题目:独一无二的出现次数

题目链接: 1207.独一无二的出现次数

题目描述

在这里插入图片描述

代码思路

根据题目要求,可以使用哈希表来统计每个数字出现的次数,然后利用set集合的特性(不能添加重复的元素)来判断是否出现重复次数

代码纯享版

class Solution {
    public boolean uniqueOccurrences(int[] arr) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int a : arr) {
            map.put(a, map.getOrDefault(a, 0) + 1);
        }
        Set<Integer> set = new HashSet<Integer>();
        for (Map.Entry<Integer, Integer> a : map.entrySet()) {
            set.add(a.getValue());
        }
        return set.size() == map.size();
    }
}


代码逐行解析版

class Solution {
    public boolean uniqueOccurrences(int[] arr) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //使用map哈希表来保存每个数字及其出现的次数
        for (int a : arr) { //遍历数组元素
            map.put(a, map.getOrDefault(a, 0) + 1); //统计数字出现次数
        }
        Set<Integer> set = new HashSet<Integer>(); //set集合,用来添加没出现过的次数
        for (Map.Entry<Integer, Integer> a : map.entrySet()) { //遍历整个map哈希表
            set.add(a.getValue()); //set集合只会添加没出现过的次数
        }
        return set.size() == map.size(); //比较set集合的长度和map哈希表的长度
    }
}


相关推荐

  1. 出现次数超过一半数(c++题解)

    2024-04-26 17:00:02       50 阅读
  2. 2211.统计道路上碰撞次数

    2024-04-26 17:00:02       27 阅读
  3. 2024.3.16每日一题——矩阵中移动最大次数

    2024-04-26 17:00:02       47 阅读
  4. 2379.得到k个黑块最少涂色次数

    2024-04-26 17:00:02       27 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-26 17:00:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-26 17:00:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-26 17:00:02       87 阅读
  4. Python语言-面向对象

    2024-04-26 17:00:02       96 阅读

热门阅读

  1. MySQL数据库子查询练习——EXISTS

    2024-04-26 17:00:02       28 阅读
  2. 前端Vue2项目搭建过程

    2024-04-26 17:00:02       33 阅读
  3. Pull和Push的关系以及区别

    2024-04-26 17:00:02       34 阅读
  4. leetcode_29.两数相除

    2024-04-26 17:00:02       33 阅读
  5. 前端深度学习Vue2框架(四)

    2024-04-26 17:00:02       38 阅读