题目描述
输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。
示例 1:
输入:arr = [3,2,1], k = 2
输出:[1,2] 或者 [2,1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Java
class Solution {
public int[] getLeastNumbers(int[] arr, int k) {
//小根堆测试,java优先队列默认是小根堆
int [] a= new int[k];
Queue<Integer> minheap=new PriorityQueue<>();
for(int c: arr){
minheap.add(c);
}
for(int i=0;i<k;i++){
a[i]=minheap.poll();
}
return a;
}
}
扩展,如果求前K个最大数,
public class Heap {
//求数组最大的K个数,用Java实现大根堆
static class MaxheapComparator implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1; //从大到小
}
}
public int [] maxHeapTest(int [] arr,int k){
int [] a= new int[k];
Queue<Integer> maxheap=new PriorityQueue<>(new MaxheapComparator());
for(int c: arr){
maxheap.add(c);
}
for(int i=0;i<k;i++){
a[i]=maxheap.poll();
}
return a;
}
//求数组最大的K个数