373. Find K Pairs with smallest Sums (Java, priority queue)

Source: Internet
Author: User

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)

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.