Find the smallest number of k in an array

Source: Internet
Author: User

Title: Enter n integers to find the smallest number of K. For example, enter 4,5,1,6,2,7,3,8 these 8 numbers, then the smallest 4 number is 1,2,3,4,.

 Packagetest;Importjava.util.ArrayList;ImportJava.util.Comparator;ImportJava.util.PriorityQueue;Importorg.junit.Test; Public classgetleastnumbers_solution {/*** Based on priority queue, time complexity is O (NLOGK) * *@paramInput *@paramK *@return     */     PublicArraylist<integer>Getleastnumbers_solutionpriorityquene (int[] Input,intk) {ArrayList<Integer> result =NewArraylist<integer>(); if(Input = =NULL|| Input.length = = 0 | | K <= 0 | | K >input.length)returnresult; Priorityqueue<Integer> maxheap =NewPriorityqueue<integer>(                NewComparator<integer>() {@Override Public intCompare (integer O1, integer o2) {returnO2.compareto (O1);        }                });  for(inti = 0; I < K; i++) {Maxheap.offer (input[i]); }         for(intj = k; J < Input.length; J + +) {            if(Input[j] <Maxheap.peek ())                {Maxheap.poll ();            Maxheap.offer (Input[j]); }        }         for(integer integer:maxheap) {result.add (integer); }        returnresult; }    /*** Based on heap ordering, time complexity is O (NLOGK) * *@paramInput *@paramK *@return     */     PublicArraylist<integer> Getleastnumbers_solutionmaxheap (int[] Input,intk) {ArrayList<Integer> result =NewArraylist<integer>(); if(Input = =NULL|| Input.length = = 0 | | K <= 0 | | K >input.length)returnresult; //Build Maximum HeapBuiltmaxheap (input,k-1);  for(inti = k; i < input.length; i++) {            //the number after the K bit of the array is smaller than the heap top            if(Input[k] < input[0]) {input[0] =Input[k]; //Adjustment HeapBuiltmaxheap (Input, k-1); }        }         for(inti = 0; I < K; i++) {Result.add (input[i]); }        returnresult; }    /*** Build and adjust the maximum heap *@paramA *@paramLastIndex*/     Public voidBuiltmaxheap (int[]a,intLastIndex) {        intParentindex = ((lastIndex-1) >> 1); //start from the parent node of the last node         for(inti=parentindex;i>=0;i--){            //child nodes exist             while(i*2+1<=LastIndex) {                intLeftindex = i*2+1; intRightindex = i*2+2; intBiggerindex =Leftindex; //There is a right node.                if(Rightindex <=LastIndex) {                    if(A[rightindex] >A[biggerindex]) {Biggerindex=Rightindex; }                }                //the maximum node in a child node is greater than the parent node                if(A[biggerindex] >A[i])                    {swap (A,i,biggerindex); I=Biggerindex; }Else{                     Break; }            }        }    }                    /*** Based on the partition function, the time complexity is O (n), the original array has been modified *@paramInput *@paramK *@return     */     PublicArraylist<integer> Getleastnumbers_solutionpartition (int[] Input,intk) {ArrayList<Integer> result =NewArraylist<integer>(); if(Input = =NULL|| Input.length = = 0 | | K <= 0 | | K >input.length)returnresult; intleft = 0; intright = Input.length-1; intindex = partition (input, 0, right);  while(Index! = k-1) {            if(Index > K-1) { Right= Index-1; Index=partition (input, left, right); } Else{ Left= index + 1; Index=partition (input, left, right); }        }         for(inti = 0; I < K; i++) {Result.add (input[i]); }        returnresult; }            /*** Partition Function *@paramA *@paramLeft *@paramRight *@return     */     Public intPartitionint[] A,intLeftintRight ) {         while(Left <Right ) {             while(Left < right && A[left] <=A[right]) { Right--; }            if(Left <Right )            {Swap (A, left, right); }             while(Left < right && A[left] <=A[right]) { Left++; }            if(Left <Right )            {Swap (A, left, right); }        }        returnLeft ; }     Public voidSwapint[] A,intIintj) {intTMP =A[i]; A[i]=A[j]; A[J]=tmp; } @Test Public voidtestgetleastnumbers_solution () {int[] A = {4, 5, 1, 6, 2, 7, 3, 8 }; intK = 4; ArrayList<Integer> list =Getleastnumbers_solutionpartition (A, k);        System.out.println (List.tostring ()); ArrayList<Integer> List2 =Getleastnumbers_solutionpriorityquene (A, k);                System.out.println (List2.tostring ()); ArrayList<Integer> List3 =Getleastnumbers_solutionmaxheap (A, k);            System.out.println (List3.tostring ()); }}

In addition to priority queueing, time complexity O (nlogk), heap ordering, time complexity O (NLOGK), partition function, time complexity is O (n) solution, and the solution based on bubble sorting time complexity is (NK).

Find the smallest number of k in an array

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.