Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions top-k-frequent-elements/hj4645.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution:
# nums 에서 가장 빈도가 높은 k개의 요소를 찾는 문제
# 딕셔너리와 정렬을 사용해 해결
# 시간복잡도: O(n log n), 공간복잡도: O(n)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

heapq나 bucket sort를 쓰면 O(n) 또는 O(n log k)로 더 빠르게 가능합니다. 물론 가독성과 정확성으로는 이 방법이 가장 좋아보이긴 합니다.

def topKFrequent(self, nums: List[int], k: int) -> List[int]:
freq_map = {}
for num in nums:
freq_map[num] = freq_map.get(num, 0) + 1

sorted_nums = sorted(freq_map.items(), key=lambda x:x[1], reverse=True)
return [num for num, _ in sorted_nums[:k]]