Skip to content

Commit ed15db0

Browse files
committed
add solution of top-k-frequent-elements
1 parent 1f42136 commit ed15db0

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)