-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain60.java
More file actions
39 lines (33 loc) · 1.03 KB
/
Main60.java
File metadata and controls
39 lines (33 loc) · 1.03 KB
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
36
37
38
39
package JZOfferTuJi;
import java.util.*;
public class Main60 {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for(int num : nums){
map.put(num, map.getOrDefault(num, 0) + 1);
}
PriorityQueue<int[]> queue = new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[1] - o2[1];
}
});
for(Map.Entry<Integer, Integer> entry: map.entrySet()){
int num = entry.getKey();
int count = entry.getValue();
if(queue.size() == k){
if(queue.peek()[1] < count){
queue.poll();
queue.offer(new int[]{num, count});
}
}else{
queue.offer(new int[]{num, count});
}
}
int[] ret = new int[k];
for(int i = 0; i<k; i++){
ret[i] = queue.poll()[0];
}
return ret;
}
}