Skip to content

Commit bae7af9

Browse files
committed
feat: add top k frequent elements solution
1 parent ecb817a commit bae7af9

File tree

1 file changed

+21
-0
lines changed
  • top-k-frequent-elements

1 file changed

+21
-0
lines changed

top-k-frequent-elements/dm.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
6+
count_dict = {}
7+
frequency_bucket = [[] for i in range(len(nums) + 1)]
8+
result = []
9+
10+
for num in nums:
11+
count_dict[num] = count_dict.get(num, 0) + 1
12+
13+
for num, count in count_dict.items():
14+
frequency_bucket[count].append(num)
15+
16+
for i in range(len(frequency_bucket) - 1, 0, -1):
17+
for num in frequency_bucket[i]:
18+
result.append(num)
19+
20+
if len(result) == k:
21+
return result

0 commit comments

Comments
 (0)