优先队列 小顶堆,大顶堆

本文介绍了Java中利用优先队列(PriorityQueue)实现寻找有序矩阵中的第K小元素、数组中的第K个最大元素以及找出数组中出现频率最高的前K个元素的方法。通过构建小顶堆和大顶堆来高效解决这些问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

堆定义

1、堆是一颗完全二叉树;

2、堆中的某个结点的值总是大于等于(最大堆)或小于等于(最小堆)其孩子结点的值。

3、堆中每个结点的子树都是堆树。

PriorityQueue<Integer> pq = new PriorityQueue<>(); 

java的优先队列数据结构,默认是小顶堆。最小元素在堆顶

第k小的值,则需要一个大顶堆

378. 有序矩阵中第 K 小的元素

    public  int kthSmallest(int[][] matrix, int k) {
//        Queue<Integer> queue = new PriorityQueue<Integer>() {
//            public int compare(Integer o1, Integer o2) {
//                return o2 - o1;
//            }
//        };//大顶堆
        Queue<Integer> queue = new PriorityQueue<Integer>((o1, o2) -> (o2 - o1));
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                queue.offer(matrix[i][j]);
                if (queue.size() > k) {
                    queue.poll();
                }
            }
        }
        return queue.peek();

    }

第k大,则需要小顶堆

215. 数组中的第K个最大元素

    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int ele : nums){
            pq.offer(ele);
            if (pq.size() > k) {
                pq.poll();
            }
        }
        return pq.peek();   
    }

 347. 前 K 个高频元素

public  int[] topKFrequent(int[] nums, int k) {
        int[] res = new int[k];
        //小顶堆
        HashMap<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);
            }
//            map.put(nums[i], map.getOrDefault(map.get(nums[i]), 0) + 1);
        }
        //按照频率排序
        Queue<Integer> queue = new PriorityQueue<>((o1, o2) -> (map.get(o1) - map.get(o2)));
        for (Integer elem : map.keySet()) {
            queue.add(elem);
            if (queue.size() > k) {
                queue.poll();
            }
        }

        int i = 0;
        while (!queue.isEmpty()) {
            res[i++] = queue.poll();
        }
        return res;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值