-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC_347
More file actions
22 lines (22 loc) · 662 Bytes
/
Copy pathLC_347
File metadata and controls
22 lines (22 loc) · 662 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int[] topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int num : nums){
map.put(num, map.getOrDefault(num, 0) + 1);
}
PriorityQueue<int[]> maxHeap = new PriorityQueue<>(
(a,b) -> b[1] - a[1]
);
for(Map.Entry<Integer,Integer> entry : map.entrySet()){
maxHeap.offer(new int[]{
entry.getKey(),
entry.getValue()
});
}
int[] ans = new int[k];
for(int i = 0; i < k; i++){
ans[i] = maxHeap.poll()[0];
}
return ans;
}
}