Skip to content

Commit ca0a2b4

Browse files
committed
[LC] feat: top k frequent elements
1 parent a2d1621 commit ca0a2b4

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

top-k-frequent-elements/hajunyoo.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from collections import defaultdict
2+
from typing import List
3+
4+
5+
class Solution:
6+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
7+
counter_dict = defaultdict(int)
8+
9+
for n in nums:
10+
counter_dict[n] += 1
11+
12+
count_list = []
13+
for key, val in counter_dict.items():
14+
count_list.append((key, val))
15+
16+
count_list.sort(key=lambda x: x[1], reverse=True)
17+
answer = [a for a, b in count_list[:k]]
18+
19+
return answer

0 commit comments

Comments
 (0)