
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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public IList<IList<int>> KSmallestPairs(int[] nums1, int[] nums2, int k) {
6 var minHeap = new SortedSet<(int sum,int i, int j)>();
7 var result = new List<IList<int>>();
8
9 for (int j = 0; j < Math.Min(k, nums2.Length); j++) {
10 minHeap.Add((nums1[0] + nums2[j], 0, j));
11 }
12
13 while (k-- > 0 && minHeap.Count > 0) {
14 var current = minHeap.Min;
15 minHeap.Remove(current);
16 int i = current.i;
17 int j = current.j;
18 result.Add(new List<int>{ nums1[i], nums2[j] });
19
20 if (i + 1 < nums1.Length) {
21 minHeap.Add((nums1[i + 1] + nums2[j], i + 1, j));
22 }
23 }
24
25 return result;
26 }
27}The C# solution uses a SortedSet to manage pairs as a min-heap, adding new potential pairs as smaller sum pairs are found. Use of tuple ensures simple structure for element sorting and extraction.
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.