首页 > 代码库 > java实现——030最小的k个数

java实现——030最小的k个数

1.O(nlogk)海量数据

 1 import java.util.TreeSet;
 2 
 3 public class T030 {
 4     public static void main(String[] args){
 5         int[] data = http://www.mamicode.com/{4,5,1,6,2,7,3,8};
 6         TreeSet<Integer> leastNumbers = new TreeSet<Integer>();
 7         getLeastNumbers(data,leastNumbers,4);
 8     
 9     }
10     public static void getLeastNumbers(int[] data,TreeSet<Integer> leastNumbers,int k){
11         leastNumbers.clear();
12         if(k<1||data.length<k)
13             return;
14         
15         for(int i=0;i<data.length;i++){
16             if(leastNumbers.size()<k)
17                 leastNumbers.add(data[i]);
18             else{
19                 System.out.println(leastNumbers.last().hashCode());
20                 if(data[i]<leastNumbers.last().hashCode()){
21                     leastNumbers.remove(leastNumbers.last());
22                     leastNumbers.add(data[i]);
23                 }
24             
25             }
26         }
27         System.out.println(leastNumbers.toString());
28     }
29 }