----------------------------------------------本题链接----------------------------------------------
题目描述
输入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;
}
}
该博客介绍了一种使用最大堆解决找到数组中最小k个数的方法。通过遍历数组,利用最大堆(优先队列)的特性,不断比较并调整堆,最终得到最小的k个数。算法过程包括异常判断、数组遍历、最大堆的构建和结果输出。示例展示了如何找出[4,5,1,6,2,7,3,8]中的最小4个数,即[1,2,3,4]。
948

被折叠的 条评论
为什么被折叠?



