剑指Offer-40-最小的k个数

剑指Offer-40-最小的k个数

堆/优先队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public int[] getLeastNumbers(int[] arr, int k) {
int len = arr.length;
int[] res = new int[k];
if(k==0) return res;
PriorityQueue<Integer> queue = new PriorityQueue<>(k, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
for (int i = 0; i < k; i++) {
queue.offer(arr[i]);
}
for (int i = k; i < len; i++) {
if (arr[i] < queue.peek()) {
queue.poll();
queue.offer(arr[i]);
}
}
for (int i = 0; i < k; i++) {
res[i] = queue.poll();
}
return res;
}