Skip to content

Commit d29c1ef

Browse files
authored
Create top_K_frequent.py
1 parent 3591597 commit d29c1ef

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

Kangli/Hash Table/top_K_frequent.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from collections import defaultdict
2+
class Solution(object):
3+
def topKFrequent(self, nums, k):
4+
"""
5+
:type nums: List[int]
6+
:type k: int
7+
:rtype: List[int]
8+
"""
9+
d = defaultdict(int)
10+
res= []
11+
for n in nums: #fill a dictionary with counts of occurence of n in nums
12+
d[n] +=1
13+
14+
15+
for w in sorted(d, key=d.get, reverse=True):
16+
res.append(w)
17+
18+
return [ res[i] for i in range(k)]

0 commit comments

Comments
 (0)