Skip to content

Commit bb75a08

Browse files
committed
top-k-frequent-elements
1 parent 01f7bb1 commit bb75a08

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

top-k-frequent-elements/bskkimm.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from collections import defaultdict
2+
class Solution:
3+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
4+
# dict_num = {num: ocurrence_num,,,,,}
5+
6+
# 1. Build the dict
7+
dict_num = defaultdict(int)
8+
for num in nums:
9+
dict_num[num] += 1
10+
11+
# 2. Resequence in the descending order w.r.t the num of ocurrence using lambda function
12+
dict_num_desc = dict(sorted(dict_num.items(), key=lambda x: x[1], reverse=True))
13+
14+
# 3. Extract top k frequent nums,,
15+
top_k = [num for i, (num, ocurrence) in enumerate(dict_num_desc.items()) if i < k]
16+
17+
return top_k

0 commit comments

Comments
 (0)