Skip to content

Commit 94823b2

Browse files
author
sangbeenmoon
committed
solved top-k-frequent-elements.
1 parent 745f661 commit 94823b2

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

top-k-frequent-elements/sangbeenmoon.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,30 @@ def topKFrequent(self, nums: List[int], k: int) -> List[int]:
2929

3030

3131

32+
# TC: O(nlogn)
33+
# SC: O(n)
34+
35+
class Solution:
36+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
37+
count_map = {}
38+
39+
for num in nums:
40+
if num in count_map:
41+
count_map[num] = count_map[num] + 1
42+
else:
43+
count_map[num] = 1
44+
45+
tuple_list = []
46+
47+
for item in count_map.items():
48+
tuple_list.append(item)
49+
50+
tuple_list.sort(key=lambda x: x[1], reverse=True)
51+
52+
answer = []
53+
for i in range(k):
54+
answer.append(tuple_list[i][0])
55+
56+
57+
return answer
58+

0 commit comments

Comments
 (0)