share my easy-understanding c++ solution


  • 0
    E

    if there is anything need to be improved, please correct me
    thanks
    class Solution {
    public:
    vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {

        vector<pair<int,int>> v;
        if(nums1.size()==0||nums2.size()==0||k==0) return v;
        for(int i = 0;i<nums1.size();i++){
            for(int j=0;j<nums2.size();j++){
                v.push_back(make_pair(nums1[i],nums2[j]));
            }
        }
        sort(v.begin(),v.end(),[&](pair<int,int> a,pair<int,int> b){
            return (a.first+a.second<b.first+b.second || (a.first+a.second==b.first+b.second)&&(a<b));
        });
        
        if(k < v.size()){
            vector<pair<int,int>>res(v.begin(),v.begin()+k);
            return res;
        }
        else 
            return v;
        
        
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.