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 2d1a0fb commit 984b209Copy full SHA for 984b209
top-k-frequent-elements/hjeomdev.java
@@ -0,0 +1,18 @@
1
+class Solution {
2
+ public int[] topKFrequent(int[] nums, int k) {
3
+ Map<Integer, Integer> map = new HashMap<>();
4
+
5
+ for (int num : nums) {
6
+ int current = map.getOrDefault(num, 0);
7
+ map.put(num, current + 1);
8
+ }
9
10
+ List<Integer> keySet = new ArrayList<>(map.keySet());
11
+ keySet.sort((o1, o2) -> map.get(o2).compareTo(map.get(o1)));
12
13
+ return keySet.subList(0, k)
14
+ .stream()
15
+ .mapToInt(Integer::intValue)
16
+ .toArray();
17
18
+}
0 commit comments