LeetCode-373 Find K Pairs with Smallest Sums

Title Description

You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.

Define a pair (u,v) which consists of one element from the first array and one element from the second array.

Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.

 

Subject to the effect

Was removed from the two given integer array sequentially two digital sum, can be taken out of a small number of the first k and the number of them into the results.

 

Examples

E1

Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Output: [[1,2],[1,4],[1,6]] 
Explanation: The first 3 pairs are returned from the sequence: 
             [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

E2

Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
Output: [1,1],[1,1]
Explanation: The first 2 pairs are returned from the sequence: 
             [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]

E3

Input: nums1 = [1,2], nums2 = [3], k = 3
Output: [1,3],[2,3]
Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]

 

Problem-solving ideas

Using a simple data structure map <int, set <pair <int, int >>>, through all the possibilities of the number, before removing the k as a result to (map automatically sorted according to the first primary parameter).

 

Complexity Analysis

Time complexity: O (M * N)

Space complexity: O (M * N)

 

Code

class Solution {
 public : 
    Vector <Vector < int >> kSmallestPairs (Vector < int > & nums1, Vector < int > & nums2, int K) { 
        Map < int , multiset <pair < int , int >>> pairSum;
         // through all possible number of pairs of numbers and their storage and 
        for ( int J = 0 ; J <nums2.size (); ++ J) {
             for ( int I = 0 ; I <nums1.size ();++i) {
                pairSum[nums1[i] + nums2[j]].insert(make_pair(nums1[i], nums2[j]));
            }
        }
        
        vector<vector<int> > res;
        // 取出上述保存的前k个数对
        for(auto iter = pairSum.begin(); iter != pairSum.end(); ++iter) {
            for(auto it = iter->second.begin(); it != iter->second.end(); ++it) {
                if(res.size() >= k)
                    break;
                vector<int> tmp;
                tmp.push_back(it->first);
                tmp.push_back(it->second);
                res.push_back(tmp);
            }
            if(res.size() >= k)
                break;
        }
        
        return res;
    }
};

 

Guess you like

Origin www.cnblogs.com/heyn1/p/11249651.html