Skip to content

Commit 476d86f

Browse files
dohee789dohee789
authored andcommitted
👔 top-k-frequent-elements solution
1 parent fd0d221 commit 476d86f

File tree

1 file changed

+31
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)