LeetCode_优先级队列_中等_373.查找和最小的 K 对数字

x33g5p2x  于2022-08-17 转载在 其他  
字(2.3k)|赞(0)|评价(0)|浏览(160)

1.题目

给定两个以升序排列的整数数组 nums1 和 nums2 , 以及一个整数 k 。

定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2 。

请找到和最小的 k 个数对 (u1, v1), (u2, v2) … (uk, vk) 。

示例 1:

输入: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
输出: [1,2],[1,4],[1,6]
解释: 返回序列中的前 3 对数:
     [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

示例 2:

输入: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
输出: [1,1],[1,1]
解释: 返回序列中的前 2 对数:
     [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]

示例 3:

输入: nums1 = [1,2], nums2 = [3], k = 3 
输出: [1,3],[2,3]
解释: 也可能序列中所有的数对都被返回:[1,3],[2,3]

提示:
1 <= nums1.length, nums2.length <= 105
-109 <= nums1[i], nums2[i] <= 109
nums1 和 nums2 均为升序排列
1 <= k <= 1000

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-k-pairs-with-smallest-sums
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2.思路

(1)优先级队列
① 定义一个优先级队列 queue(默认是大根堆,需自己改写为小根堆) ,里面的元素为题目中的数对。
② 将 nums1.length * nums2.length 个数对存放到 queue 中;
③ 选取 queue 中前 k 个数对(如果有)和最小的数对并将它们保存到 res 中,最后再返回 res 即可。

不过在 LeetCode 中提交时会出现“超出内存限制”的提示!仔细分析后可知:题目只要求出和最小的 k 个数对,而 queue 中却保存了 nums1.length * nums2.length 个数对,当 nums1.length * nums2.length >> k 时,显然就浪费了内存空间。所以方法 2 对此进行了优化。

(2)优先级队列(优化)
思路参考本题官方题解

3.代码实现(Java)

//思路1————优先级队列
class Solution {
    public static List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        List<List<Integer>> res = new ArrayList<>();
        PriorityQueue<List<Integer>> queue = new PriorityQueue<>((list1, list2) -> {
            return list1.get(0) + list1.get(1) - list2.get(0) - list2.get(1);
        });
        //将所有可能的数对存放到 queue 中
        for (int i = 0; i < nums1.length; i++) {
            for (int j = 0; j < nums2.length; j++) {
                List<Integer> tmp = new ArrayList<>();
                tmp.add(nums1[i]);
                tmp.add(nums2[j]);
                queue.offer(tmp);
            }
        }
        //选取 queue 中前 k 个数对和最小的数对
        while (k != 0 && !queue.isEmpty()) {
            res.add(queue.poll());
            k--;
        }
        return res;
    }
}
//思路2————优先级队列(优化)
class Solution {
    public static List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) { 
        List<List<Integer>> res = new ArrayList<>();
        PriorityQueue<int[]> queue = new PriorityQueue<>(k, (o1, o2) -> {
            return nums1[o1[0]] + nums2[o1[1]] - nums1[o2[0]] - nums2[o2[1]];
        });
        for (int i = 0; i < Math.min(nums1.length, k); i++) {
            queue.offer(new int[]{i, 0});
        }
        while (k-- != 0 && !queue.isEmpty()) {
            int[] idxPair = queue.poll();
            List<Integer> list = new ArrayList<>();
            list.add(nums1[idxPair[0]]);
            list.add(nums2[idxPair[1]]);
            res.add(list);
            if (idxPair[1] + 1 < nums2.length) {
                queue.offer(new int[]{idxPair[0], idxPair[1] + 1});
            }
        }
        return res;
    }
}

相关文章

微信公众号

最新文章

更多