Topic:
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.
Analysis: before K small combination, the size between the combination is the size of the data pair and. Also take priority queue, the first element of the team is a smaller value.
Code:
Public classSolution { Publiclist<int[]> Ksmallestpairs (int[] nums1,int[] Nums2,intk) {if(Nums1 = =NULL|| NUMS2 = =NULL|| K <= 0) return NULL; if(Nums1.length = = 0 | | nums2.length = = 0) return Newarraylist<int[]>(); if(Nums1.length * Nums2.length <k) K= Nums1.length *nums2.length; //The priorityqueue priority queuepriorityqueue<pair> queue =NewPriorityqueue<pair>(); //resultlist<int[]> list =Newarraylist<int[]>(); //first Combine all nums1 with nums2[0] into the queue for(inti = 0; i < nums1.length; ++i) Queue.add (NewPair (i,0,nums1[i],nums2[0])); //get K Minimum value for(intn = 0; n < K; ++N) {Pair tmp=Queue.poll (); int[] ele = Tmp.pair;//value pairsList.add (ele);//Join the result set if(TMP.J = = Nums2.length-1) Continue; Queue.add (NewPair (TMP.I,TMP.J + 1,NUMS1[TMP.I],NUMS2[TMP.J + 1])); } returnlist; }}//defining the data structure of a pairclassPairImplementsComparable<pair>{ int[] pair =New int[2];//Define Array Pairs inti;// the subscript of the first element in a nums1intJ;// The subscript of the second element in a NUMS2 PublicPair (intIintJintE1,intE2) {pair[0] =E1; pair[1] =E2; This. i =i; This. J =J; } @Override Public intCompareTo (Pair that) {//Ascending order return(Pair[0] + pair[1])-(that.pair[0] + that.pair[1]); }}
373. Find K Pairs with smallest Sums (Java, priority queue)