Skip to content

Commit c5c2c17

Browse files
committed
top-k-frequent-elements
1 parent 2a9041e commit c5c2c17

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+
import java.util.HashMap;
2+
import java.util.Map;
3+
import java.util.PriorityQueue;
4+
5+
public class runnz121 {
6+
7+
public class Solution {
8+
9+
public int[] topKFrequent(int[] nums, int k) {
10+
11+
Map<Integer, Integer> map = new HashMap<>();
12+
13+
for (int i = 0; i < nums.length; i++) {
14+
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
15+
}
16+
17+
PriorityQueue<Integer> maxPq = new PriorityQueue<>(
18+
(a, b) -> map.get(b) - map.get(a)
19+
);
20+
21+
maxPq.addAll(map.keySet());
22+
23+
int[] result = new int[k];
24+
25+
for (int i = 0; i < k; i++) {
26+
result[i] = maxPq.poll();
27+
}
28+
return result;
29+
}
30+
}
31+
}

0 commit comments

Comments
 (0)