-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy path347.java
More file actions
22 lines (21 loc) · 767 Bytes
/
347.java
File metadata and controls
22 lines (21 loc) · 767 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> h = new HashMap<>();
PriorityQueue<Pair<Integer,Integer>> minPQ = new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());
for(int i=0;i<nums.length;i++){
int freq = h.getOrDefault(nums[i], 0) + 1;
h.put(nums[i], freq);
}
for(HashMap.Entry<Integer, Integer> e : h.entrySet()){
minPQ.add(new Pair(e.getKey(), e.getValue()));
if(minPQ.size() > k){
minPQ.remove();
}
}
int[] res = new int[k];
for(int i=0; i < k;i++){
res[i] = minPQ.remove().getKey();
}
return res;
}
}