从零学算法347

13 篇文章 0 订阅
9 篇文章 0 订阅
文章介绍了如何使用HashMap统计整数数组中每个元素的出现次数,然后利用优先队列(最大堆或最小堆)找到出现频率最高的k个元素,分别展示了两种方法的实现细节。
摘要由CSDN通过智能技术生成

347.给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]

  • 思路就是记录每个数出现的个数,然后取出现频率前 k 高的数,无非就是使用的方法不同。这里先用 HashMap 记录每个数出现次数,再用优先队列根据出现次数降序排序,最后取前 k 个
  •   public int[] topKFrequent(int[] nums, int k) {
          //先统计每个数字出现的次数
          Map<Integer, Integer> map = new HashMap<>();
          for (int num : nums)
              map.put(num, map.getOrDefault(num, 0) + 1);
    
          //最大堆
          PriorityQueue<int[]> priorityQueue = new PriorityQueue<>((a, b) -> b[1] - a[1]);
          for (int key : map.keySet())
              priorityQueue.add(new int[]{key, map.get(key)});
    
          //取堆中最大的k个元素
          int[] res = new int[k];
          for (int i = 0; i < k; i++)
              res[i] = priorityQueue.poll()[0];
          return res;
      }
    
  • 用最小堆也差不多同理,只是往堆中添加元素时如果堆的长度大于 k 就移除堆顶元素即可(移除出现次数不够多的)。
  •   public int[] topKFrequent(int[] nums, int k) {
          //先统计每个数字出现的次数
          Map<Integer, Integer> map = new HashMap<>();
          for (int num : nums)
              map.put(num, map.getOrDefault(num, 0) + 1);
    
          //最小堆
          PriorityQueue<int[]> priorityQueue = new PriorityQueue<>((a, b) -> a[1] - b[1]);
          for (int key : map.keySet()) {
              priorityQueue.add(new int[]{key, map.get(key)});
              if (priorityQueue.size() > k)
                  priorityQueue.poll();
          }
    
          //把堆中的元素转化为数组
          int[] res = new int[k];
          int index = 0;
          while (!priorityQueue.isEmpty()) {
              res[index++] = priorityQueue.poll()[0];
          }
          return res;
      }
    
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值