Skip to content

Commit a054fb1

Browse files
committed
[:solved] top-k-frequent-elements
1 parent 6670e7e commit a054fb1

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

top-k-frequent-elements/ppxyn1.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# idea: dictonary
2+
3+
class Solution:
4+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
5+
count_dict = {}
6+
ans = []
7+
for idx, val in enumerate(nums):
8+
if val not in count_dict:
9+
count_dict[val] = 1
10+
else:
11+
count_dict[val] +=1
12+
sorted_items = sorted(count_dict.items(), key=lambda x: x[1], reverse=True) #sorted return list / dict.items() is tuple
13+
# print(sorted_items)
14+
for i in range(k):
15+
ans.append(sorted_items[i][0])
16+
return ans
17+
18+
'''
19+
Similar way : Using Counter() function
20+
'''
21+

0 commit comments

Comments
 (0)