0
点赞
收藏
分享

微信扫一扫

LeetCode-前 K 个高频元素(优先队列)

伊人幽梦 2022-03-31 阅读 52

前言:

  • 啥是优先队列?
  • 优先队列的实现原理

题目:

在这里插入图片描述

思路:

  • 常规的解法就是将值存放并记录在hash表中,并且最好按照value进行排序
  • 但是TreeMap是无法进行队value进行排序的,此时就需要借助优先队列,来实现对map中的value进行排序
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer,Integer> map=new HashMap<>();
        for(int t:nums){
            map.put(t,map.getOrDefault(t,0)+1);
        }
        PriorityQueue<Map.Entry<Integer,Integer>> queue=new PriorityQueue<>((t1,t2)->t2.getValue()-t1.getValue());
        // 1,3  2,4  3,5
        for(Map.Entry<Integer,Integer> entry : map.entrySet()){
            queue.add(entry);
        }
        int[] ans=new int[k];
        for(int i=0;i<k;i++){
            ans[i]=queue.poll().getKey();
        }

        return ans;
    }
}
举报

相关推荐

0 条评论