Skip to content

Commit 3566525

Browse files
committed
剑指 Offer 40. 最小的k个数
1 parent 01a9adb commit 3566525

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.geekidentity.leetcode.offer.sort;
2+
3+
import java.util.PriorityQueue;
4+
import java.util.Queue;
5+
6+
/**
7+
* 排序
8+
* 剑指 Offer 40. 最小的k个数
9+
* https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/
10+
*/
11+
public class Offer40GetLeastNumbers {
12+
public int[] getLeastNumbers(int[] arr, int k) {
13+
if (arr == null || arr.length == 0 || k == 0) {
14+
return new int[0];
15+
}
16+
17+
Queue<Integer> maxStack = new PriorityQueue<>((a, b) -> b - a);
18+
for (int i : arr) {
19+
if (maxStack.size() < k) {
20+
maxStack.offer(i);
21+
} else if (maxStack.peek() > i) {
22+
maxStack.poll();
23+
maxStack.offer(i);
24+
}
25+
}
26+
int[] result = new int[maxStack.size()];
27+
int i = 0;
28+
for (Integer n : maxStack) {
29+
result[i++] = n;
30+
}
31+
return result;
32+
}
33+
}

0 commit comments

Comments
 (0)