Skip to content

Commit 49a60fe

Browse files
authored
Update Top K Frequent Elements - Leetcode 347.java
1 parent ad49bf0 commit 49a60fe

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,47 @@
1+
import java.util.*;
2+
3+
public class Solution {
4+
public int[] topKFrequent(int[] nums, int k) {
5+
Map<Integer, Integer> countMap = new HashMap<>();
6+
for (int num : nums) {
7+
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
8+
}
9+
10+
PriorityQueue<Map.Entry<Integer, Integer>> heap = new PriorityQueue<>(
11+
(a, b) -> Integer.compare(a.getValue(), b.getValue())
12+
);
13+
14+
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
15+
if (heap.size() < k) {
16+
heap.offer(entry);
17+
} else {
18+
heap.offer(entry);
19+
heap.poll();
20+
}
21+
}
22+
23+
int[] topK = new int[k];
24+
for (int i = k - 1; i >= 0; i--) {
25+
topK[i] = heap.poll().getKey();
26+
}
27+
28+
return topK;
29+
}
30+
}
31+
32+
33+
34+
35+
36+
37+
38+
39+
40+
41+
42+
43+
44+
145
import java.util.*;
246

347
public class Solution {

0 commit comments

Comments
 (0)