Leetcode 查找和最小的 K 对数字

java 实现

java 复制代码
class Solution {
    public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        //首先创建一个存储结果的二维数组
        List<List<Integer>> result = new ArrayList<>();
        //特殊情况处理
        if(nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
            return result;
        }

        //然后初始化优先队列, 
        //其中a[0] b[0]是数对中第一个数字在数组 nums1 中的索引, a[1] b[1]是数对中第二个数字在数组 nums2 中的索引
        PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> (nums1[a[0]] + nums2[a[1]]) - (nums1[b[0]] + nums2[b[1]]));
        //初始化堆,先让 nums1 的前 k 个元素和 nums2[0] 配对加入堆
        for(int i = 0; i < Math.min(nums1.length, k); i++) {
            minHeap.offer(new int[]{i, 0});
        }

        //然后取出前 k 小的数对
        while(k-- > 0 && !minHeap.isEmpty()) {
            //堆顶元素出队
            int[] pair = minHeap.poll();
            int i = pair[0], j = pair[1];

            List<Integer> currentPair = new ArrayList<>();
            currentPair.add(nums1[i]);
            currentPair.add(nums2[j]);
            result.add(currentPair);

            //如果 nums2 中还有下一个元素, 加入堆
            //这一部分代码片段在往堆中添加元素时,会根据最小堆设定的规则动态调整堆的堆顶元素位置
            //所以上面初始化堆时,先让 nums1 的前 k 个元素和 nums2[0] 配对加入堆也会得到正确的结果。
            if(j + 1 < nums2.length) {
                minHeap.offer(new int[]{i, j + 1});
            }
        }

        return result;

        
    }
}
相关推荐
轻松Ai享生活1 小时前
5 节课深入学习Linux Cgroups
linux
Fanxt_Ja2 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下2 小时前
最终的信号类
开发语言·c++·算法
christine-rr2 小时前
linux常用命令(4)——压缩命令
linux·服务器·redis
茉莉玫瑰花茶2 小时前
算法 --- 字符串
算法
三坛海会大神5552 小时前
LVS与Keepalived详解(二)LVS负载均衡实现实操
linux·负载均衡·lvs
東雪蓮☆2 小时前
深入理解 LVS-DR 模式与 Keepalived 高可用集群
linux·运维·服务器·lvs
博笙困了2 小时前
AcWing学习——差分
c++·算法
NAGNIP2 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP2 小时前
大模型微调框架之LLaMA Factory
算法