C++, idea of using multimap


  • 0
    class Solution {
    public:
        vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
            multimap<int, pair<int, int>> map;
            vector<pair<int, int>> res;
            if (nums1.size() == 0 || nums2.size() == 0) return res;
            for (int i = 0; i < min((int)nums1.size(), k); ++i) 
                for (int j = 0; j < min((int)nums2.size(), k); ++j) 
                    map.insert(make_pair(nums1[i] + nums2[j], make_pair(nums1[i], nums2[j])));
            auto it = map.begin();
            while (k > 0 && it != map.end()) {
                res.push_back(it->second);
                --k;
                ++it;
            }
            return res;
        }
    };
    

    Just provide another idea of solving this problem.


Log in to reply
 

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