----------------------------------------------本题链接----------------------------------------------
题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
示例
输入
[4,5,1,6,2,7,3,8],4
返回值
[1,2,3,4]
思路
数组排序问题,考虑使用最大堆的堆排序
遍历数组,每次只和堆顶比,如果比堆顶小,删除堆顶,新数入堆
算法过程
- 判断异常情况
- 数组遍历,用最大堆存储
- 输出结果
解答
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> res = new ArrayList<>();
if(input.length == 0 || k == 0 || k > input.length) return res;
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k, new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2){
return o2.compareTo(o1);
}
});
for(int x : input){
if(maxHeap.size() < k){
maxHeap.offer(x);
} else {
if(maxHeap.peek() > x){
int tmp = maxHeap.poll();
maxHeap.offer(x);
}
}
}
for(int x : maxHeap){
res.add(x);
}
return res;
}
}