Skip to content

Commit 317d899

Browse files
authored
Merge pull request #3054 from AkifhanIlgaz/0347
0347-top-k-frequent-elements.dart
2 parents 775606f + f8fe611 commit 317d899

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

dart/0347-top-k-frequent-elements.dart

+28
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,31 @@
1+
class Solution {
2+
List<int> topKFrequent(List<int> nums, int k) {
3+
Map<int, int> frequencyMap = {};
4+
for (int num in nums) {
5+
frequencyMap[num] = (frequencyMap[num] ?? 0) + 1;
6+
}
7+
8+
List<List<int>> frequencyList =
9+
List.filled(nums.length + 1, List<int>.empty(growable: true));
10+
11+
frequencyMap.forEach((num, count) {
12+
frequencyList[count] = [...frequencyList[count], num];
13+
});
14+
15+
List<int> res = [];
16+
17+
for (var i = frequencyList.length - 1; i >= 0; i--) {
18+
res.addAll(frequencyList[i]);
19+
20+
if (res.length == k) {
21+
break;
22+
}
23+
}
24+
25+
return res;
26+
}
27+
}
28+
129
class Solution {
230
List<int> topKFrequent(List<int> nums, int k) {
331
Map<int, int> map = {};

0 commit comments

Comments
 (0)