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 1f42136 commit ed15db0Copy full SHA for ed15db0
top-k-frequent-elements/jinhyungrhee.java
@@ -0,0 +1,29 @@
1
+import java.util.*;
2
+import java.util.stream.*;
3
+
4
+class Solution {
5
+ public int[] topKFrequent(int[] nums, int k) {
6
7
+ Map<Integer, Integer> map = new HashMap<>();
8
+ for(int n : nums) {
9
+ if(!map.containsKey(n)) {
10
+ map.put(n, 1);
11
+ } else {
12
+ map.put(n, map.get(n) + 1);
13
+ }
14
15
16
+ Map<Integer, Integer> sortedMap = map.entrySet().stream()
17
+ .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
18
+ .collect(Collectors.toMap(
19
+ Map.Entry::getKey,
20
+ Map.Entry::getValue,
21
+ (oldVal, newVal) -> oldVal,
22
+ LinkedHashMap::new
23
+ ));
24
25
+ List<Integer> list = sortedMap.keySet().stream().limit(k).toList();
26
+ return list.stream().mapToInt(Integer::intValue).toArray();
27
28
+}
29
0 commit comments