Skip to content

Commit d9d6dbc

Browse files
committed
🐛 top-k-frequent-elements Solution
1 parent b5734ce commit d9d6dbc

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import java.util.*;
2+
class Solution {
3+
public int[] topKFrequent(int[] nums, int k) {
4+
Map<Integer, Integer> map = new HashMap<>();
5+
6+
7+
for(int i : nums) {
8+
map.put(i, map.getOrDefault(i,0) + 1);
9+
}
10+
11+
PriorityQueue<Map.Entry<Integer, Integer>> pq =
12+
new PriorityQueue<>(Comparator.comparingInt(Map.Entry::getValue));
13+
14+
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
15+
pq.offer(entry);
16+
if (pq.size() > k) {
17+
pq.poll(); // Remove the least frequent element
18+
}
19+
}
20+
21+
// Step 3: Extract the elements from the heap
22+
int[] result = new int[k];
23+
for (int i = k - 1; i >= 0; i--) {
24+
result[i] = pq.poll().getKey();
25+
}
26+
27+
return result;
28+
29+
}
30+
}

0 commit comments

Comments
 (0)