• 力扣347(前k个高频元素)


    347、前k个高频元素 

    基本思想:

    对频率进行排序,

    使用优先级队列

    具体实现:

    什么是优先级队列呢?

    1、对外接口从队头取元素,从队尾添加元素,再无其他取元素的方式

    2、优先级队列内部元素是自动依照元素的权值排列。

    如何有序排列?

    使用堆

    堆是一颗完全二叉树,树中每个结点的值都不小于(或不大于)其左右孩子的值。 

    如果父亲结点是大于等于左右孩子就是大顶堆,小于等于左右孩子就是小顶堆。

    此题用小顶堆,因为要统计最大前k个元素,只有小顶堆每次将最小的元素弹出,最后小顶堆里积累的才是前k个最大元素。

    代码:

    class Solution {
        public int[] topKFrequent(int[] nums, int k) {
            int[] result = new int[k];
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int num : nums){
                map.put(num, map.getOrDefault(num, 0) + 1);
                // map.put,将指定key-value添加到(或修改)当前map对象中
                //map.getOrDefault,当map集合中有这个num时,就使用这个num值;如果没有就使用0。
            }
            Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
            //Set entrySet():返回所有key-value对构成的Set集合
            PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue());
            for (Map.Entry<Integer, Integer> entry : entries) {
                queue.offer(entry);
                if (queue.size() > k) {
                    queue.poll();
                }
            }
             // 找出前K个高频元素,因为小顶堆先弹出的是最小的,所以倒叙来输出到数组
            // for (int i = k - 1; i >= 0; i--) {
            //     result[i] = queue.poll().getKey();
            // }
            // return result;
            for (int i = 0; i < k; i++) {
                result[i] = queue.poll().getKey();
            }
            return result;
        }
    }
  • 相关阅读:
    POJ 1095 Trees Made to Order 最详细的解题报告
    Producter and Consumer
    How to use the function of bind
    How to use the functions of apply and call
    Configurate vim tool
    #4713. 方程
    #4709. 树
    #4718. 管理
    #4710. 并
    #4707. 点分治
  • 原文地址:https://www.cnblogs.com/zhaojiayu/p/15510823.html
Copyright © 2020-2023  润新知