给定一个数组,取出其中最小的K个数。
适合大数据场景。
package practice;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Topk {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num[] = {3,4,5,6,7,8,4,2,5,66,4,4,6,3,5,6,74,56,5,7,5,7,6,4,3,4,5,4,3};
System.out.println(new Topk().getTopK(num, 3).toString());
}
public ArrayList<Integer> getTopK(int num[],int k){
ArrayList<Integer> res = new ArrayList<>();
if(num.length<k){
return res;
}
PriorityQueue<Integer> pr=new PriorityQueue<>(k, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
for(int i = 0;i<num.length;i++){
pr.add(num[i]);
}
for(int i =0;i<k;i++){
res.add(pr.remove());
}
return res;
}
}