-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBM46.java
More file actions
30 lines (28 loc) · 838 Bytes
/
BM46.java
File metadata and controls
30 lines (28 loc) · 838 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
package NiukeTOP101;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
public class BM46 {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> result = new ArrayList<>();
if(input.length == 0 || k ==0){
return result;
}
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(k, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
for (int j : input) {
maxHeap.add(j);
if(maxHeap.size() > k){
maxHeap.poll();
}
}
while (!maxHeap.isEmpty()){
result.add(maxHeap.poll());
}
return result;
}
}