查找和最小的 K 对数字

链接

class Solution {
    public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        PriorityQueue<List<Integer>> maxHeap = new PriorityQueue<>(k, new Comparator<List<Integer>>() {
            @Override
            public int compare(List<Integer> o1, List<Integer> o2) {
                return (o2.get(0)+o2.get(1))-(o1.get(0)+o1.get(1));
            }
        });
       for (int i = 0; i < Math.min(nums1.length,k); i++) {
           for (int j = 0; j < Math.min(nums2.length,k); j++) {
                if(maxHeap.size() < k) {
                    List<Integer> tmpList = new ArrayList<>();
                    tmpList.add(nums1[i]);
                    tmpList.add(nums2[j]);
                    maxHeap.offer(tmpList);
                }else {
                    int top = maxHeap.peek().get(0) + maxHeap.peek().get(1);
                    if(top > nums1[i]+nums2[j]) {
                        // 先弹出 后进入
                        maxHeap.poll();
                        List<Integer> tmpList = new ArrayList<>();
                        tmpList.add(nums1[i]);
                        tmpList.add(nums2[j]);
                        maxHeap.offer(tmpList);
                    }
                }
            }
        }
        List<List<Integer>> ret = new ArrayList<>();
        for (int i = 0; i < k && !maxHeap.isEmpty(); i++) {
            ret.add(maxHeap.poll());
        }
        return ret;
    }
}
可以用 Kotlin 实现一个小根堆来解决这个问题。首先,我们可以将 nums1 中的每个数与 nums2 中的第一个数组合成一对,并将其加入小根堆中。然后,我们每次从堆中取出和最小的数对 (u, v),并将 nums1 中和 u 相邻的数和 nums2 中和 v 相邻的数组成的数对加入堆中。重复这个步骤 k 次即可得到和最小的 k 个数对。 以下是 Kotlin 实现的代码: ```kotlin import java.util.* fun kSmallestPairs(nums1: IntArray, nums2: IntArray, k: Int): List<List<Int>> { val heap = PriorityQueue<List<Int>>(compareBy { it[0] + it[1] }) for (i in nums1.indices) { heap.offer(listOf(nums1[i], nums2[0], 0)) } val result = mutableListOf<List<Int>>() for (i in 0 until k) { val pair = heap.poll() ?: break result.add(listOf(pair[0], pair[1])) if (pair[2] == nums2.size - 1) continue heap.offer(listOf(pair[0], nums2[pair[2] + 1], pair[2] + 1)) } return result } ``` 这个函数接受三个参数:两个整数数组 nums1 和 nums2,以及一个整数 k。它返回一个包含最小的 k 个数对的列表。在函数内部,我们首先创建一个小根堆 heap,并将 nums1 中的每个数与 nums2 中的第一个数组合成一对并加入堆中。然后,我们循环 k 次,每次从堆中取出和最小的数对 (u, v),将其加入结果列表 result 中,并将 nums1 中和 u 相邻的数和 nums2 中和 v 相邻的数组成的数对加入堆中。最后,我们返回结果列表 result。 参考资料: - LeetCode 题目 373. 查找最小的 K 对数字 - Kotlin 标准库中的 PriorityQueue 类
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值