首页 > 其他分享 >【优先队列】LeetCode 347. 前 K 个高频元素

【优先队列】LeetCode 347. 前 K 个高频元素

时间:2023-01-08 11:55:22浏览次数:54  
标签:Map num map 队列 priorityQueue int 347 new LeetCode

题目链接

347. 前 K 个高频元素

思路

前k大模板题

代码

class Solution{
    public int[] topKFrequent(int[] nums, int k){
        PriorityQueue<Map.Entry<Integer, Integer>> priorityQueue = new PriorityQueue<>(
                new Comparator<Map.Entry<Integer, Integer>>(){
                    @Override
                    public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2){
                        return Integer.compare(o1.getValue(), o2.getValue());
                    }
                });
        Map<Integer, Integer> map = new HashMap<>();

        for(Integer num : nums){
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        for(Map.Entry<Integer, Integer> entry : map.entrySet()){
            priorityQueue.add(entry);
            if(priorityQueue.size() > k){
                priorityQueue.poll();
            }
        }
        
        int[] result = new int[k];
        for(int i = 0; i < k; i++){
            result[i] = priorityQueue.poll().getKey();
        }

        return result;
    }

}

标签:Map,num,map,队列,priorityQueue,int,347,new,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17034357.html

相关文章

  • 【优先队列】LeetCode 973. 最接近原点的 K 个点
    题目链接973.最接近原点的K个点思路使用优先队列处理前k大问题代码classSolution{classNode{intx;inty;doubledistance;......
  • LeetCode每日一题1.8
    2185.CountingWordsWithaGivenPrefixhttps://leetcode.cn/problems/counting-words-with-a-given-prefix/官方题解:https://leetcode.cn/problems/counting-words-w......
  • [C++/Java/Py/C#/Ruby/Swift/Go/Scala/Kotlin/Rust/PHP/TS/Elixir/Dart/Racket/Erlang
    目录题解地址代码cppjavapython3C#rubyswiftgolangscalakotlinrustphptypescriptelixirdartracketerlang题解地址https://leetcode.cn/problems/counting-words-with-a-g......
  • [LeetCode] 149. Max Points on a Line
    Givenanarrayof points where points[i]=[xi,yi] representsapointonthe X-Y plane,return themaximumnumberofpointsthatlieonthesamestraig......
  • leetcode-1658. 将 x 减到 0 的最小操作数
    正向双指针有点麻烦,但是能通过,先提交一下,待我学习一下其他的解法再来提交这个里面不用对opNum进行计数,可以利用left和right的位置计算出来左右两边的长度,可以省略一些,这......
  • 单调队列
    单调队列前言图床在\(Github\)中,如果访问不了\(Github\),则图片无法加载引入原题链接:P1886滑动窗口/【模板】单调队列-洛谷题意简述:有一个长度为\(n\)的数......
  • 代码随想录day10 LeetCode20 有效的括号 1047. 删除字符串中的所有相邻重复项
     LeetCode20有效的括号 https://leetcode.cn/problems/valid-parentheses/submissions/流程为遍历每一个字符并判断是否为左括号还是有括号,若为左括号则放入栈中,若为......
  • [leetcode每日一题]1.7
    ​​1658.将x减到0的最小操作数​​难度中等给你一个整数数组 ​​nums​​ 和一个整数 ​​x​​ 。每一次操作时,你应当移除数组 ​​nums​​ 最左边或最右边......
  • 栈和队列
    栈一般数组和链表两种实现方式栈:先进后出、尾入尾出classStack{private:int*data;//存放栈中的数据intmaxsize;//栈最大空间inttop;//栈顶pu......
  • 【哈希表】LeetCode 299. 猜数字游戏
    题目链接299.猜数字游戏思路建立两个哈希表分别存储secret和guess中不是bulls的数字出现次数。代码classSolution{publicStringgetHint(Stringsecret,......