373. 查找和最小的 K 对数字
两种解法
class Solution {
public:vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {auto cmp = [&](const vector<int> &a,const vector<int> &b){return a[0] > b[0];};priority_queue<vector<int>,vector<vector<int>>,decltype(cmp)> minheap(cmp);for(int i=0;i< min (k,(int)nums1.size());++i){minheap.push({nums1[i]+nums2[0],i,0});}vector<vector<int>> ans;while(k-- && !minheap.empty() ){auto t = minheap.top();minheap.pop();int sum = t[0];int i = t[1], j = t[2];ans.push_back({nums1[i],nums2[j]});if(j+1 < nums2.size()){minheap.push({nums1[i]+nums2[j+1],i,j+1});}}return ans;}
};
struct node{int num1;int num2;int i1;int i2;bool operator < (const node m)const{return num1 + num2 > m.num1 + m.num2;}
};class Solution {
public:vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {vector<vector<int>> ans;set<pair<int,int>> st;priority_queue<node> que;que.push({nums1[0],nums2[0],0,0});while(!que.empty() && ans.size() < k){auto t = que.top();que.pop();int num1 = t.num1;int num2 = t.num2;ans.push_back({num1,num2});int i1 = t.i1;int i2 = t.i2;if(i1+1<nums1.size() && !st.count({i1+1,i2})){st.insert({i1+1,i2});que.push({nums1[i1+1],nums2[i2],i1+1,i2});}if(i2+1<nums2.size() && !st.count({i1,i2+1})){st.insert({i1,i2+1});que.push({nums1[i1],nums2[i2+1],i1,i2+1});}}return ans;}
};