
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.
1#include <vector>
2#include <queue>
3using namespace std;
4
5vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
6 priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> minHeap;
7 vector<vector<int>> result;
8
9 for (int j = 0; j < min(k, static_cast<int>(nums2.size())); j++) {
10 minHeap.push({nums1[0] + nums2[j], {0, j}});
11 }
12
13 while (k-- > 0 && !minHeap.empty()) {
14 auto current = minHeap.top();
15 minHeap.pop();
16 int i = current.second.first;
17 int j = current.second.second;
18 result.push_back({nums1[i], nums2[j]});
19
20 if (i + 1 < nums1.size()) {
21 minHeap.push({nums1[i + 1] + nums2[j], {i + 1, j}});
22 }
23 }
24
25 return result;
26}The C++ solution efficiently processes pairs using a min-heap. For each step, it extracts the smallest sum and adds potential new pairs to the heap to continue finding the k smallest pairs.
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.
using System.Collections.Generic;
public class Solution {
public IList<IList<int>> KSmallestPairs(int[] nums1, int[] nums2, int k) {
var pairs = new List<(int sum, int num1, int num2)>();
for (int i = 0; i < nums1.Length; i++) {
for (int j = 0; j < nums2.Length; j++) {
pairs.Add((nums1[i] + nums2[j], nums1[i], nums2[j]));
}
}
pairs.Sort((a, b) => a.sum.CompareTo(b.sum));
var result = new List<IList<int>>();
for (int i = 0; i < Math.Min(k, pairs.Count); i++) {
result.Add(new List<int> { pairs[i].num1, pairs[i].num2 });
}
return result;
}
}C# implementation uses tuples and simple sorting to derive the top k pairs after comprehensive pair list generation. Simple and illustrative but computationally intensive.