File tree 1 file changed +33
-0
lines changed
src/main/java/com/geekidentity/leetcode/offer/sort
1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments