Skip to content

Commit e68bd88

Browse files
committed
feat: top-k-frequent-elements solution
1 parent c53e52c commit e68bd88

File tree

1 file changed

+27
-0
lines changed

1 file changed

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

Comments
 (0)