373. Find K Pairs with smallest Sums

Source: Internet
Author: User

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&LT;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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.