输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
方法一:
对于海量的数据 用大顶堆
public class Solution {
public static class Acomp implements Comparator<Integer>{
public int compare(Integer o1,Integer o2){
return o2-o1;//要搞大顶堆
}
}
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> arr=new ArrayList<Integer>();
if(input==null||k<=0||k>input.length)
return arr;//注意!!!!!
PriorityQueue<Integer> queue=new PriorityQueue<Integer>(new Acomp());
int index=0;
while(queue.size()<k){
queue.offer(input[index++]);
}
for(;index<input.length;index++){
if(input[index]<queue.peek()){
queue.poll();
queue.offer(input[index]);
}
}
for(Integer i:queue){
arr.add(i);
}
return arr;
}
}
每次可以在O(1)时间内得到已有的K个数字中的最大值,但需要O(logk)时间完成删除及插入操作。对于n个数字,时间复杂度为O(nlogk)
方法二:
数组快排(改变快排里的l r) 返回的index==k为止 这时左边K个数字就是最小的K个数字