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
E2
E3
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; } };