- https://www.cnblogs.com/64open/p/5267678.html
- 在priority_queue中使用匿名函数的正确姿势:
bool cmp(const pair<int,int>& a, const pair<int,int>& b){return a.first + a.second > b.first + b.second;}
class Solution {
struct mycompare{
bool operator()(pair<int,int>& a, pair<int,int>& b){
return a.first + a.second > b.first + b.second;
}
};
public:
vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
int sz1 = nums1.size();
int sz2 = nums2.size();
// priority_queue<Node, vector<Node>, cmp> q;
// priority_queue<pair<int,int>, vector<pair<int, int>>, mycompare> pq;
auto cmp2 = [](const pair<int,int>& a, const pair<int,int>& b){return a.first + a.second > b.first + b.second;};
priority_queue<pair<int,int>, vector<pair<int, int>>, decltype(cmp2)> pq(cmp2);
for(auto a : nums1) for(auto b : nums2) pq.push({a, b});
vector<pair<int, int>> ret;
while(!pq.empty() && int(ret.size()) < k){
ret.push_back(pq.top());
pq.pop();
}
// -------------------------test-------------------------------
// vector<int> test = {1,3,4,2,5,6,4,3,6,4,6,7,4,7,3};
// // sort(test.begin(), test.end(), [](int a, int b){return a > b;});
// sort(test.begin(), test.end(), cmp);
// for(auto a : test) cout<<a<<' ';
// -------------------------test-------------------------------
return ret;
}
};