LeetCode之堆

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

class Solution {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> queue = new PriorityQueue<>(k);

        for (int num : nums) {
            if (queue.size() < k) {
                queue.offer(num);
            } else if (num > queue.peek()) {
                queue.poll();
                queue.offer(num);
            }
        }
        return queue.peek();

    }
}

373. 查找和最小的 K 对数字

import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;

class Solution {
    public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        // 创建一个优先队列,按照两数之和从小到大排序
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] + a[1] - b[0] - b[1]);
        List<List<Integer>> result = new ArrayList<>();

        // 如果任一数组为空,直接返回空列表
        if (nums1.length == 0 || nums2.length == 0) {
            return result;
        }

        // 将第一组数字和第二组数字的第一个元素&索引的组合放入优先队列
        for (int i = 0; i < nums1.length && i < k; i++) {
            pq.offer(new int[]{nums1[i], nums2[0], 0});
        }

        // 取出最小的 K 个组合
        while (k > 0 &&!pq.isEmpty()) {
            int[] pair = pq.poll();
            result.add(List.of(pair[0], pair[1]));
            if (pair[2] < nums2.length - 1) {
                // 如果还可以从第二个数组取下一个数字组成新的组合,放入优先队列
                pq.offer(new int[]{pair[0], nums2[pair[2] + 1], pair[2] + 1});
            }
            k--;
        }

        return result;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值