We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent b5734ce commit d9d6dbcCopy full SHA for d9d6dbc
top-k-frequent-elements/dalpang81.java
@@ -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