Skip to content

Commit f3b6c8d

Browse files
committed
Find K Pairs with smallest sum
1 parent 39135a0 commit f3b6c8d

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// we will be solving the question Find K Pairs with Smallest Sums
2+
#include<iostream>
3+
#include<vector>
4+
#include<algorithm>
5+
#include<array>
6+
#include<queue>
7+
using namespace std;
8+
vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k){
9+
vector<vector<int>> result;
10+
priority_queue<array<int, 3>, vector<array<int, 3>>, greater<array<int, 3>>> minHeap;
11+
if(nums1.empty() || nums2.empty() || k == 0){
12+
return result;
13+
}
14+
for(int i = 0; i < nums1.size() && i < k ; i++){
15+
minHeap.push({nums1[i] + nums2[0], i, 0});
16+
}
17+
while(k > 0 && !minHeap.empty()){
18+
auto curr = minHeap.top();
19+
minHeap.pop();
20+
k--;
21+
int i = curr[1];
22+
int j = curr[2];
23+
result.push_back({nums1[i], nums2[j]});
24+
if(j + 1 < nums2.size()){
25+
minHeap.push({nums1[i] + nums2[j + 1], i , j + 1});
26+
}
27+
}
28+
return result;
29+
}
30+
int main(){
31+
int n ;
32+
int m;
33+
cout << "Enter the value of n: " << endl;
34+
cin >> n;
35+
cout << "Enter the value of m: " << endl;
36+
cin >> m;
37+
vector<int> nums1(n);
38+
vector<int> nums2(m);
39+
cout << "Enter the elemets of nums1 : " << endl;
40+
for(int i = 0 ; i < n; i++){
41+
cin >> nums1[i];
42+
}
43+
cout << "Enter the elements of nums2 : " << endl;
44+
for(int i = 0; i < m; i++){
45+
cin >> nums2[i];
46+
}
47+
int k;
48+
cout << "Enter the value of K: " << endl;
49+
cin >> k;
50+
vector<vector<int>> result = kSmallestPairs(nums1, nums2, k);
51+
cout << "The " << k << " pairs with smallest sums are as: " << endl;
52+
for(const auto& pair : result){
53+
cout << "[" << pair[0] << ", " << pair[1] << "]" << endl;
54+
}
55+
cout << endl;
56+
return 0;
57+
}

0 commit comments

Comments
 (0)