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 c53e52c commit e68bd88Copy full SHA for e68bd88
top-k-frequent-elements/sm9171.java
@@ -0,0 +1,27 @@
1
+class Solution {
2
+ public int[] topKFrequent(int[] nums, int k) {
3
+ Map<Integer, Integer> hashMap = new HashMap<>();
4
+ for (int i = 0; i < nums.length; i++) {
5
+ int num = nums[i];
6
+ if (hashMap.containsKey(num)) {
7
+ hashMap.put(num, hashMap.get(num) + 1);
8
+ continue;
9
+ }
10
+ hashMap.put(num, 1);
11
12
+
13
+ List<Integer> list = hashMap.entrySet()
14
+ .stream()
15
+ .sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
16
+ .limit(k)
17
+ .map(Map.Entry::getKey)
18
+ .toList();
19
20
+ int [] result = new int[list.size()];
21
+ for (int i = 0; i < list.size(); i++) {
22
+ result[i] = list.get(i);
23
24
25
+ return result;
26
27
+}
0 commit comments