题目:
给定两个以升序排列的整数数组 nums1 和 nums2 , 以及一个整数 k 。
定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2 。
请找到和最小的 k 个数对 (u1,v1), (u2,v2) ... (uk,vk) 。
示例 1:
示例 2:
示例 3:
提示:
代码:
class Solution {
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
List<List<Integer>> res = new ArrayList<>();
Queue<int[]> queue = new PriorityQueue<>(
(m, n) -> nums1[m[0]] + nums2[m[1]] - nums1[n[0]] - nums2[n[1]]
);
for (int i = 0; i < Math.min(k, nums1.length); i++) {
queue.offer(new int[]{i, 0});
}
for(; k > 0 && !queue.isEmpty(); k--) {
int[] temp = queue.poll();
res.add(Arrays.asList(nums1[temp[0]], nums2[temp[1]]));
if (temp[1] + 1 < nums2.length) {
queue.add(new int[]{temp[0], temp[1] + 1});
}
}
return res;
}
}
解题思路:
首先这道题肯定是要使用堆来解决的,至于堆中存储下标还是具体数字,都是可以的,在本题中我使用的是下标,因为可以在把第一个数组全部放入堆中以后很方便的把第二个数组中的数再依次放入堆中。首先把第一个数组中的每个数和第二个数组中的第一个数的组合放入堆中,然后每次取出队头,再把第二个数组的下一个数和第一个数组的组合放入堆中。
注意:
早睡早起,熬夜伤身体。
参考链接:
力扣