-
-
Notifications
You must be signed in to change notification settings - Fork 335
Expand file tree
/
Copy pathppxyn1.py
More file actions
21 lines (18 loc) · 612 Bytes
/
ppxyn1.py
File metadata and controls
21 lines (18 loc) · 612 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# idea: dictonary
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count_dict = {}
ans = []
for idx, val in enumerate(nums):
if val not in count_dict:
count_dict[val] = 1
else:
count_dict[val] +=1
sorted_items = sorted(count_dict.items(), key=lambda x: x[1], reverse=True) #sorted return list / dict.items() is tuple
# print(sorted_items)
for i in range(k):
ans.append(sorted_items[i][0])
return ans
'''
Similar way : Using Counter() function
'''