Find the smallest number of top k in a bunch of numbers

Source: Internet
Author: User
Tags sort
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:



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.