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

时间:2024-08-10 09:35:20

1.O(nlogk)海量数据

 import java.util.TreeSet;

 public class T030 {
public static void main(String[] args){
int[] data = {4,5,1,6,2,7,3,8};
TreeSet<Integer> leastNumbers = new TreeSet<Integer>();
getLeastNumbers(data,leastNumbers,4); }
public static void getLeastNumbers(int[] data,TreeSet<Integer> leastNumbers,int k){
leastNumbers.clear();
if(k<1||data.length<k)
return; for(int i=0;i<data.length;i++){
if(leastNumbers.size()<k)
leastNumbers.add(data[i]);
else{
System.out.println(leastNumbers.last().hashCode());
if(data[i]<leastNumbers.last().hashCode()){
leastNumbers.remove(leastNumbers.last());
leastNumbers.add(data[i]);
} }
}
System.out.println(leastNumbers.toString());
}
}

相关文章