373. Find K Pairs with smallest Sums
You are given the 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.
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]
Hide Tags
Heap
Public classSolution { Publiclist<int[]> Ksmallestpairs (int[] nums1,int[] Nums2,intk) {List<int[]> ret =NewArraylist<>(); if(Nums1.length = = 0 | | nums2.length = = 0 | | k = = 0) { returnret; } //Num2index keeps the index of next number in Nums2, that would pair with the value in Nums1 int[] Num2index =New int[Nums1.length]; intNum1start = 0; while(k--> 0) { //every time we find a min, we'll restart from the first number in NUMS1. intCurrentmin =Integer.max_value; intFound =-1; for(inti = Num1start; i < nums1.length; ++i) {if(Num2index[i] >= nums2.length) {//Nums[i] has been fully paired.Num1start = i;//we only need to start to I for the next min search Continue; } intNextmin = Nums1[i] +Nums2[num2index[i]]; if(Nextmin <currentmin) {Currentmin=nextmin; Found=i; } } if(found = =-1) returnRet//cannot find any more pairs, which mean k are larger than total combination countsRet.add (New int[]{nums1[found], Nums2[num2index[found]]}); Num2index[found]++;//set the corresponding index to next one } returnret; }}
373. Find K Pairs with smallest Sums