c++ solution


  • 1
    H
    class Solution {
    public:
        vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
            k = min(k, int(nums1.size() * nums2.size()));
            vector<pair<int, int>> ret;
            int m = nums1.size();
            vector<int> index(m, 0);
            for(int i = 0; i < k; ++i){
                int p1 = 0, sum = INT_MAX;
                for(int j = 0; j < nums1.size(); ++j){
                    if(index[j] < nums2.size() && sum >= nums1[j] + nums2[index[j]]){
                        p1 = j;
                        sum = nums1[j] + nums2[index[j]];
                    }
                }
                ret.push_back(make_pair(nums1[p1], nums2[index[p1]]));
                index[p1]++;
            }
            return ret;
        }
    };
    

Log in to reply
 

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