Skip to content

Commit ee7f941

Browse files
committed
top k frequent elements solution(py)
1 parent 4842af2 commit ee7f941

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# 가장 자주 등장한 상위 K개의 문자 배열 반환
2+
# O(n log n) time, O(n) space
3+
4+
from collections import defaultdict
5+
6+
class Solution:
7+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
8+
numdict = defaultdict(int);
9+
result = []
10+
11+
for num in nums:
12+
if num in numdict:
13+
numdict[num] += 1
14+
else:
15+
numdict[num] = 1
16+
17+
sort_dict = dict(sorted(numdict.items(), key=lambda item: item[1], reverse=True))
18+
19+
keys = list(sort_dict)
20+
21+
return keys[:k]

0 commit comments

Comments
 (0)