You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
Define a pair (u,v) which consists of one element from the first array and one element from the second array.
Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.
public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
Queue<int[]> pq = new PriorityQueue<>((a,b) -> a[1] + a[0] - b[1] - b[0]);
List<int[]> res = new ArrayList<>();
if (nums1.length == 0 || nums2.length == 0 || k == 0) return res;
for (int i = 0; i < nums1.length && i < k; i++) pq.offer(new int[] {nums1[i], nums2[0], 0});
while (k-- > 0 && !pq.isEmpty()) {
int[] cur = pq.poll();
int idx = cur[2];
res.add(new int[] {cur[0], cur[1]});
if (idx == nums2.length - 1) continue;
pq.offer(new int[] {cur[0], nums2[idx + 1], idx + 1});
}
return res;
}
本文介绍了一种使用优先队列寻找两个有序整数数组中和最小的k对元素的方法。通过维护一个优先队列来保证每次都能选取当前状态下两数组组合中和最小的一对,并继续探索该对元素所在列的下一个可能的最小和对。
125

被折叠的 条评论
为什么被折叠?



