
Sponsored
Sponsored
This approach utilizes a min-heap to efficiently get the smallest sums. We initialize the heap with pairs consisting of the first element from nums1 and each element from nums2. We then extract the minimum sum from the heap, track the index of the element from nums2, and push the next pair from nums1 onto the heap. Repeat the process until we've found k pairs or exhausted possibilities.
Time Complexity: O(k * log(min(k, n))) where n is the length of nums2.
Space Complexity: O(min(k, m*n)) used by the heap where m and n are the lengths of nums1 and nums2, respectively.
1import java.util.*;
2
3class Solution {
4 public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
5 List<List<Integer>> result = new ArrayList<>();
6 PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
7
8 for (int j = 0; j < Math.min(k, nums2.length); j++) {
9 minHeap.offer(new int[] {nums1[0] + nums2[j], 0, j});
10 }
11
12 while (k > 0 && !minHeap.isEmpty()) {
13 int[] cur = minHeap.poll();
14 result.add(Arrays.asList(nums1[cur[1]], nums2[cur[2]]));
15
16 if (cur[1] + 1 < nums1.length) {
17 minHeap.offer(new int[] {nums1[cur[1] + 1] + nums2[cur[2]], cur[1] + 1, cur[2]});
18 }
19 k--;
20 }
21
22 return result;
23 }
24}The Java solution uses a PriorityQueue (as a min-heap) to store pairs of indices and their sums. It iteratively finds and removes the smallest sum (top of the heap), adding the next possible smallest pair to the queue.
In this naive approach, we first generate all possible pairs and their sums, storing them in a list. After generating the pairs, we sort them based on their sums and simply return the first k pairs. This approach, while straightforward, is computationally expensive for large input sizes.
Time Complexity: O(m * n * log(m * n)) where m and n are the lengths of nums1 and nums2, respectively.
Space Complexity: O(m * n) for storing all pairs.
In this Python example, all pairwise sums are precomputed and stored in a list, which is then sorted to extract the first k pairs. The computational cost is high due to full pair generation and sorting.