-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
33 lines (27 loc) · 791 Bytes
/
Solution.java
File metadata and controls
33 lines (27 loc) · 791 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
class Solution {
class Node {
int num;
int freq;
Node(int num, int freq) {
this.num = num;
this.freq = freq;
}
}
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Node> map = new HashMap<>();
PriorityQueue<Node> pq = new PriorityQueue<>((a, b) -> b.freq - a.freq);
int[] ans = new int[k];
for (int i = 0; i < nums.length; i++) {
Node cur = map.getOrDefault(nums[i], new Node(nums[i], 0));
cur.freq += 1;
map.put(nums[i], cur);
}
for (var entry : map.entrySet()) {
pq.add(entry.getValue());
}
for (int i = 0; i < k; i++) {
ans[i] = pq.poll().num;
}
return ans;
}
}