Time limit: 1 seconds Space limit: 32768K topic description 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,. The simplest of course is direct ordering, the first number of K is the title of the request, but this is obviously not a good solution. can choose to use the partition function of the fast row, simple division, but do not sort, more quickly solve the problem.
Importjava.util.ArrayList; Public classSolution { PublicArraylist<integer> Getleastnumbers_solution (int[] Input,intk) {ArrayList<Integer> result=NewArraylist<integer>(); if(k<=0){ returnresult; } if(input.length==0| | input.length<k) { returnresult; } intStart=0; intEnd=input.length-1; intindex=Partition (input,start,end); while(index!=k-1){ if(index>k-1) {End=index-1; Index=Partition (input,start,end); }Else{Start=index+1; Index=Partition (input,start,end); } } for(inti=0;i<k;i++) {Result.add (input[i]); } returnresult; } Public intPartition (int[] Input,intStartintend) { intpivot=Input[start]; while(start<end) { while(Start<end&&input[end]>=pivot) {--end;} Input[start]=Input[end]; while(Start<end&&input[start]<=pivot) {++start;} Input[end]=Input[start]; } Input[end]=pivot; returnend; }}
The
can also consider using another data structure, the largest heap, save this k number with the largest heap, each time only and heap top ratio, if smaller than the heap top, delete the heap top, the new number into the heap.
Import Java.util.arraylist;import Java.util.priorityqueue;import Java.util.comparator;public class Solution {public Arraylist<integer> getleastnumbers_solution (int[] input, int k) {arraylist<integer> result = new ArrayL Ist<integer> (); int length = Input.length; if (k > Length | | k = = 0) {return result; } priorityqueue<integer> maxheap = new priorityqueue<integer> (k, new comparator<integer> () { @Override public int Compare (integer o1, integer o2) {return O2.compareto (O1); } }); for (int i = 0; i < length; i++) {if (maxheap.size ()! = k) {Maxheap.offer (input[i]); } else if (Maxheap.peek () > Input[i]) {Integer temp = Maxheap.poll (); temp = null; Maxheap.offer (Input[i]); }} for (an Integer integer:maxheap) {Result.add (inTeger); } return result; }}
Minimum number of k in Java---