Skip to content

Commit 8acdf4b

Browse files
committed
Top K Frequent Elements solution
1 parent 0c700f0 commit 8acdf4b

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

top-k-frequent-elements/doh6077.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class Solution:
2+
# dictionary use
3+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
4+
result = {} # key: 원소, value: 등장 횟수
5+
for n in nums:
6+
if n in result:
7+
result[n] = result[n] + 1
8+
else:
9+
result[n] = 1
10+
11+
# 가장 자주 등장한 원소 k개 반환
12+
return sorted(result.keys(), key=lambda x: result[x], reverse=True)[:k]

0 commit comments

Comments
 (0)