Input: nums1 =[1,7,11], nums2 =[2,4,6], k =3Output: [[1,2],[1,4],[1,6]]Explanation: The first 3 pairs are returned from the sequence:[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
Input: nums1 =[1,1,2], nums2 =[1,2,3], k =2Output: [[1,1],[1,1]]Explanation: The first 2 pairs are returned from the sequence:[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
We use a min heap to always select the next smallest sum pair. By expanding only the next possible pairs, we avoid generating all possible pairs, making the solution efficient.
classSolution {
public List<List<Integer>>kSmallestPairs(int[] nums1, int[] nums2, int k) {
List<List<Integer>> ans =new ArrayList<>();
if (nums1.length== 0 || nums2.length== 0 || k == 0) return ans;
PriorityQueue<int[]> pq =new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
for (int i = 0; i < Math.min(nums1.length, k); i++)
pq.offer(newint[]{nums1[i]+nums2[0], i, 0});
while (!pq.isEmpty() && ans.size() < k) {
int[] p = pq.poll();
ans.add(Arrays.asList(nums1[p[1]], nums2[p[2]]));
if (p[2]+1 < nums2.length)
pq.offer(newint[]{nums1[p[1]]+nums2[p[2]+1], p[1], p[2]+1});
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funkSmallestPairs(nums1: List<Int>, nums2: List<Int>, k: Int): List<List<Int>> {
val ans = mutableListOf<List<Int>>()
if (nums1.isEmpty() || nums2.isEmpty() || k ==0) return ans
val pq = PriorityQueue(compareBy<Pair<Int, Int>> { nums1[it.first] + nums2[it.second] })
for (i in0 until minOf(nums1.size, k)) pq.add(Pair(i, 0))
while (pq.isNotEmpty() && ans.size < k) {
val(i, j) = pq.poll()
ans.add(listOf(nums1[i], nums2[j]))
if (j+1 < nums2.size) pq.add(Pair(i, j+1))
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
defk_smallest_pairs(nums1: list[int], nums2: list[int], k: int) -> list[list[int]]:
ans = []
ifnot nums1 ornot nums2 or k ==0:
return ans
heap = []
for i in range(min(len(nums1), k)):
heapq.heappush(heap, (nums1[i]+nums2[0], i, 0))
while heap and len(ans) < k:
_, i, j = heapq.heappop(heap)
ans.append([nums1[i], nums2[j]])
if j+1< len(nums2):
heapq.heappush(heap, (nums1[i]+nums2[j+1], i, j+1))
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnk_smallest_pairs(nums1: Vec<i32>, nums2: Vec<i32>, k: i32) -> Vec<Vec<i32>> {
letmut ans =vec![];
if nums1.is_empty() || nums2.is_empty() || k ==0 { return ans; }
letmut heap = BinaryHeap::new();
for i in0..nums1.len().min(k asusize) {
heap.push(Reverse((nums1[i]+nums2[0], i, 0)));
}
whilelet Some(Reverse((_, i, j))) = heap.pop() {
ans.push(vec![nums1[i], nums2[j]]);
if ans.len() == k asusize { break; }
if j+1< nums2.len() {
heap.push(Reverse((nums1[i]+nums2[j+1], i, j+1)));
}
}
ans
}
}