题目
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
思路
1 利用大顶堆保存这k个数
2 遍历input数组,每次与堆顶元素比较,若堆顶元素比较大,则删除堆顶元素,把input元素加入堆
import java.util.*;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> ans=new ArrayList();
if(k<1||k>input.length)
return ans;
PriorityQueue <Integer> maxHead=new PriorityQueue<Integer>(k,new Comparator<Integer>(){
public int compare(Integer o1,Integer o2){
return o2.compareTo(o1);
}
});
for(int i=0;i<input.length;i++){
if(maxHead.size()!=k)
maxHead.offer(input[i]);
else{
if(maxHead.peek()>input[i])
{
maxHead.poll();
maxHead.offer(input[i]);
}
}
}
for(Integer i:maxHead)
ans.add(i);
return ans;
}
}
来源:CSDN
作者:jcjcjcjiangcheng
链接:https://blog.csdn.net/jcjcjcjiangcheng/article/details/104105865