find the smallest number of top k in a bunch of numbers
Describe:
Given an array of integers, let you find the smallest number of k from the array
Ideas:
The simplest and most brutal way is to sort the array and take the first number of K. However, the only thing required is to find the smallest number of k, with the sort can be but a little wasted, such as the 10,000 integer array of the smallest 10 numbers, the average time to sort the complexity of the difference is Nlog (N).
So think of, with the heap to achieve, but oneself realize and too troublesome, think of Java inside of TreeSet, first put K number into TreeSet, because TreeSet will order the elements inside, so in TreeSet element is ordered, after not inserted an element, The largest element in the TreeSet is removed, so the TreeSet dynamically maintains the k element and the K element is ordered.
Code: Copy
import Java.util.TreeSet;
Public class Firstkelements
{
Public Static Treeset<integer>getfirstkelements (int arr[],int k)
{
treeset<integer>set=New treeset<integer> ();
int len=arr.length;
K=k%len;
int i=0;
int num=0;
for (i=0;i<k;i++)
Set.add (Arr[i]);
for (i=k;i<len;i++)
{
Set.add (Arr[i]);
Num=set.last ();
Set.remove (num);
}
return set;
}
Public Static void Main (string[] args)
{
TODO auto-generated Method Stub
int arr[]={9,7,5,4,2,1,3,6,8};
System.out.println (Firstkelements.getfirstkelements (arr, 4));
}
}
Results: