forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetLeastNumbers.java
More file actions
35 lines (32 loc) · 893 Bytes
/
GetLeastNumbers.java
File metadata and controls
35 lines (32 loc) · 893 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package map;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
public class GetLeastNumbers {
public static void main(String[] args) {
int[] arr = {3,2,1};
int k = 2;
int[] r = getLeastNumbers(arr,k);
System.out.println(Arrays.toString(r));
}
private static int[] getLeastNumbers(int[] arr, int k) {
if(k == 0 || arr.length == 0){
return new int[0];
}
Queue<Integer> pq = new PriorityQueue<>((v1,v2) -> (v2-v1));
for (int num : arr){
if(pq.size() < k){
pq.offer(num);
}else if (num < pq.peek()){
pq.poll();
pq.offer(num);
}
}
int[] rex = new int[pq.size()];
int idx = 0;
for (int a : pq){
rex[idx++] = a;
}
return rex;
}
}