Discussion of Top K issues (Java implementation of three methods and scope of application)

Source: Internet
Author: User

In a lot of written tests and interviews, like to examine the top K. The following from their own experience to give three ways of implementation and practical scope.

    • Merger law

This method is suitable for the case of several arrays in order to find the top K. The time complexity is O (k*m). (m: Number of arrays). The specific implementation is as follows:

/*** Several descending ordered m arrays are known, and the number of k large before these data is suitable for merge method and time complexity (O (k*m);*/Importjava.util.List;Importjava.util.Arrays;Importjava.util.ArrayList; Public classtopkbymerge{ Public int[] GETTOPK (List<list<integer>>input,intk) {    intindex[]=New int[Input.size ()];//saves the position of each array subscript scan;    intresult[]=New int[K];  for(inti=0;i<k;i++){       intmax=Integer.min_value; intMaxindex=0;  for(intJ=0;j<input.size (); j + +){           if(index[j]<Input.get (j). Size ()) {                if(max<Input.get (j). Get (Index[j])) {Max=Input.get (j). Get (Index[j]); Maxindex=J; }           }       }       if(max==integer.min_value) {           returnresult; } Result[i]=Max; Index[maxindex]+=1; }    returnresult;} 
    • Quick-Arrange Process method

The fast-track process uses the process of fast sequencing to find top K. The average time complexity is (O (K*LOGN). Applies to unordered single arrays. The specific Java implementation is as follows:

/** Use the fast sequencing process to find the smallest number of K **/ Public classtopk{intPartion (intA[],intFirstintend) {        intI=First ; intmain=A[end];  for(intj=first;j<end;j++){             if(a[j]<Main) {                inttemp=A[j]; A[J]=A[i]; A[i]=temp; I++; }} A[end]=A[i]; A[i]=main; returni; }   voidGettopkminbysort (intA[],intFirstintEndintk) {      if(first<end) {          intpartionindex=partion (a,first,end); if(partionindex==k-1)return; Else if(partionindex>k-1) Gettopkminbysort (a,first,partionindex-1, K); ElseGettopkminbysort (a,partionindex+1, end,k); }   } Public Static voidMain (String []args) {inta[]={2, -,3,7,9,1, -, -,0,4}; intk=6; NewTopK (). Gettopkminbysort (A,0, a.length-1, K);  for(intI=0; i<k;i++) {System. out. Print (a[i]+" "); }   }}
    • Using a small Gan or a large root heap

The maximum k is used in small Gan, and the minimum k is used in large root heap.

The maximum number of steps for K:

    1. According to the data before the K-node to establish a small Gan.
    2. In the subsequent scan of the n-k data,
    • If the data is larger than the root node of the small Gan, the value of the root node is covered with that data and the node is adjusted to the small Gan.
    • If the data is less than or equal to the root node of the small Gan, the small Gan does not change.

The minimum k is similar to this one for Max K. Time complexity O (NLOGK) (n: The length of the data), especially for top K for big data.

/*** Ask for the largest K solution in front: small Gan (with a large amount of data (especially if the memory is not able to hold), preferring to use a heap) * *  */ Public classTopK {/*** Create a small Gan of k nodes * *@paramA *@paramK *@return     */    int[] Createheap (intA[],intk) {int[] result =New int[K];  for(inti = 0; I < K; i++) {Result[i]=A[i]; }         for(inti = 1; I < K; i++) {            intChild =i; intParent = (i-1)/2; inttemp =A[i];  while(Parent >= 0 &&child!=0&& Result[parent] >temp) {Result[child]=Result[parent]; Child=parent; Parent= (parent-1)/2; } Result[child]=temp; }        returnresult; }    voidInsertintA[],intvalue) {a[0]=value; intParent=0;  while(parent<a.length) {             intLchild=2*parent+1; intRchild=2*parent+2; intminindex=parent; if(lchild<a.length&&a[parent]>A[lchild]) {Minindex=Lchild; }             if(rchild<a.length&&a[minindex]>A[rchild]) {Minindex=Rchild; }             if(minindex==parent) {                  Break; }Else{                 inttemp=A[parent]; A[parent]=A[minindex]; A[minindex]=temp; Parent=Minindex; }         }             }    int[] Gettopkbyheap (intInput[],intk) {intHeap[] = This. Createheap (input, k);  for(inti=k;i<input.length;i++){            if(input[i]>heap[0]){                 This. Insert (heap, input[i]); }                            }        returnHeap; }     Public Static voidMain (string[] args) {intA[] = {4, 3, 5, 1, 2,8,9,10}; intResult[] =NewTopK (). Gettopkbyheap (A, 3);  for(intTemp:result)        {System.out.println (temp); }    }}

Discussion of Top K issues (Java implementation of three methods and scope of application)

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.