Skip to content

Commit 07a2c17

Browse files
committed
solve 0347-top-k-frequent-elements.dart
1 parent 2868340 commit 07a2c17

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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+
}

0 commit comments

Comments
 (0)