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;

        
    }
}
相关推荐
iuu_star6 分钟前
C语言数据结构-顺序查找、折半查找
c语言·数据结构·算法
Yzzz-F13 分钟前
P1558 色板游戏 [线段树 + 二进制状态压缩 + 懒标记区间重置]
算法
漫随流水20 分钟前
leetcode算法(515.在每个树行中找最大值)
数据结构·算法·leetcode·二叉树
Sean X1 小时前
Ubuntu24.04安装向日葵
linux·ubuntu
mit6.8241 小时前
dfs|前后缀分解
算法
扫地的小何尚1 小时前
NVIDIA RTX PC开源AI工具升级:加速LLM和扩散模型的性能革命
人工智能·python·算法·开源·nvidia·1024程序员节
IT 乔峰2 小时前
脚本部署MHA集群
linux·shell
dz小伟2 小时前
execve() 系统调用深度解析:从用户空间到内核的完整加载过程
linux
千金裘换酒2 小时前
LeetCode反转链表
算法·leetcode·链表
Mr_Xuhhh3 小时前
博客标题:深入理解Shell:从进程控制到自主实现一个微型Shell
linux·运维·服务器