-
Notifications
You must be signed in to change notification settings - Fork 0
/
K_Pairs_With_Largest_Sums.cpp
69 lines (54 loc) · 1.68 KB
/
K_Pairs_With_Largest_Sums.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
/*1. write a structure to sort according to sum values for heap
2. Data Type pushed into heap is pair<int,int>
*/
class Largest_Sums
{
public:
struct SumCompare
{
bool operator()(const pair<int,int> &x, const pair<int,int> &y)
{
return x.first+s.second>y.first+y.second;
}
};
vector<pair<int,int>> Find_K_Largest(vector<int> &nums1, vector<int> &nums2, int k)
{
priority_queue<pair<int,int>, vector<pair<int,int>>, SumCompare()> minheap;
for(int i=0;i<nums1.size() && i<k ;i++)
{
for(int j=0; j<nums2.size() && j<k ; j++)
{
if(minheap.size()<k)
{
minheap.push_back({nums1[i],nums2[j]});
push_heap(minheap.begin(),minheap.end(),SumCompare());
}
else{
if(nums1[i]+nums2[j] < minheap.front().first+minheap.front().second)
{
break;
}
else
{
pop_heap(minheap.begin(),minheap.end(),SumCompare());
minheap.pop_back();
minheap.push_back(make_pair(nums1[i],nums2[j]));
push_heap(minheap.begin(),minheap.end(), SumCompare());
}
}
}
}
return minheap;
}
};
int main()
{
auto result=Largest_Sums::Find_K_Largest({{9,8,2},{6,3,1},3});
for(auto pair: result)
{
cout<<pair.first<<pair.second;
}
}