Skip to content

Commit 6ae4bbe

Browse files
committed
feat: top k frequent elements
1 parent 5dd3628 commit 6ae4bbe

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public int[] topKFrequent(int[] nums, int k) {
3+
Map<Integer, Integer> count = new HashMap<>();
4+
for(int num : nums){
5+
count.put(num, count.getOrDefault(num, 0)+1);
6+
}
7+
List<Integer> tops = count.keySet().stream()
8+
.sorted((i1, i2) -> count.get(i2)-count.get(i1))
9+
.limit(k)
10+
.toList();
11+
12+
int[] answer = new int[k];
13+
for(int i=0; i<k; i++) {
14+
answer[i] = tops.get(i);
15+
}
16+
return answer;
17+
}
18+
}

0 commit comments

Comments
 (0)