zoukankan      html  css  js  c++  java
  • LeetCode347. 前 K 个高频元素

    class Solution {
        public List<Integer> topKFrequent(int[] nums, int k) {
            //先统计每个数字出现的频率
            
            
            Map<Integer,Integer> map = new HashMap<>();
            for(int i = 0; i < nums.length ; i++)
            {
                if(map.containsKey(nums[i]))
                {
                    map.put(nums[i], map.get(nums[i]) + 1);
                }
                else
                {
                    map.put(nums[i] , 1);
                }
            }
    
    
            //根据出现的次数构造小顶堆,把次数少的放在堆顶
            PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>()
            {
                public int compare(Integer a, Integer b)
                {
                    return map.get(a) - map.get(b);
                }
            });
    
            for(int key : map.keySet())
            {
                if(pq.size() < k)
                {
                    pq.add(key);
                }
                else if(map.get(key) > map.get(pq.peek()))
                {
                    pq.remove();//直接删除,因为只需要K个
                    pq.add(key);
                }
            }
            List<Integer> res = new ArrayList<>();
            while (!pq.isEmpty())
            {
                res.add(pq.remove());
            }
            return res;
    
        }
    }
  • 相关阅读:
    v-for基本使用
    SSH
    Git 命令
    bower笔记
    gulp使用例子
    yeoman使用例子
    grunt搭建
    不会误解的名字
    Python 多线程 多进程
    Python 协程
  • 原文地址:https://www.cnblogs.com/swqblog/p/12878476.html
Copyright © 2011-2022 走看看