1、前言
2、思路
使用大根堆的思路,主要大根堆的这段代码,节省时间:new PriorityQueue<>((o1, o2) -> o2 - o1);
3、代码
class Solution {
public int[] getLeastNumbers(int[] arr, int k) {
if(k == 0 || arr.length == 0){
return new int[]{};
}
PriorityQueue<Integer> minHeap = new PriorityQueue<>((o1, o2) -> o2 - o1);
for(int i = 0; i < k; i++){
minHeap.offer(arr[i]);
}
for(int i = k; i < arr.length; i++){
if(arr[i] < minHeap.peek()){
minHeap.poll();
minHeap.offer(arr[i]);
}
}
int[] res = new int[k];
for(int i = 0; i < k; i++){
res[i] = minHeap.poll();
}
return res;
}
}