题目 :输入n个整数,找出其中最小的K个数。 例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4
遍历数组先取数组的前k个数建立大根堆,继续遍历数组.如果当前值比大根堆最大值小,那么将数组中这个小值替换到堆里.
//输入n个整数,找出其中最小的K个数。
// 例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
public static ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> list=new ArrayList<Integer>();
if (input==null){
return list;
}
if (input.length<k||k==0){
return list;
}
PriorityQueue<Integer> maxHeap=new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
});
//2,41,5,2,5,3,4,23
for(int i=0;i<input.length;i++){
if (i<k){
maxHeap.add(input[i]);
}
else if (maxHeap.peek()>input[i]){
maxHeap.poll();
maxHeap.add(input[i]);
}
}
while (!maxHeap.isEmpty())
{
list.add(maxHeap.poll());
}
return list;
}