You are given the integer arrays nums1 and nums2 sorted in ascending order and an integer K.
Give you two arrays of nums1 and NUMS2, both of which are ascending, and give you an integer k.
Define a pair (U,V) which consists of one element from the first array and one element from the second array.
Define a pair (U,V) where one of the numbers is in the first array, and the other dozens of in the second array.
Find the K pairs (U1,V1), (U2,V2) ... (UK,VK) With the smallest sums.
Find the two numbers in all pair and the top K pair arranged by small to large.
Example 1:
Given nums1 = [1,7,11], NUMS2 = [2,4,6], k = 3Return: [1,2],[1,4],[1,6]the first 3 pairs is returned from the Sequenc e:[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
Example 2:
Given nums1 = [1,1,2], NUMS2 = [], k = 2Return: [1,1],[1,1]the first 2 pairs is returned from the sequence:[1,1] , [1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
Example 3:
Given nums1 = [up], NUMS2 = [3], k = 3 Return: [1,3],[2,3]all possible pairs is returned from the sequence:[1,3],[2, 3]
1 classSolution {2 Public:3vector<pair<int,int>> Ksmallestpairs (vector<int>& Nums1, vector<int>& Nums2,intk) {4vector<pair<int,int>>ret;5 if(Nums1.empty () | | Nums2.empty ())returnret;6 intL1=nums1.size (), l2=nums2.size ();7vector<int> mm (L1,0);8 for(intCount=0, low=0; count<k&&mm[l1-1]<L2;) {9 inttmpi=low,tmpms=nums1[low]+Nums2[mm[low]];Ten for(inti=low+1; i<l1;i++){ One if(MM[I]==L2)Continue; A inttmp=nums1[i]+Nums2[mm[i]]; - if(TMP<TMPMS) {tmpms=tmp;tmpi=i;} - if(mm[i]==0) Break; the } -Ret.push_back (pair<int,int>(Nums1[tmpi],nums2[mm[tmpi] )); -mm[tmpi]++; - if(MM[LOW]==L2) low++; +count++; - } + returnret; A } at};
Above is the AC code, not very will write explanation, also trouble, have the problem can message me.
373. Find K Pairs with smallest Sums