사용자 도구

사이트 도구


ps:problems:leetcode:347

Top K Frequent Elements

ps
링크leetcode.com/…
출처LeetCode
문제 번호347
문제명Top K Frequent Elements
레벨Medium
분류

기본

시간복잡도O(n+klogn)
인풋사이즈n<=10^5
사용한 언어python 3.14
제출기록22.91MB / 3ms
최고기록0ms
해결날짜2026/04/25

풀이

  • 그냥 시키는대로 하면 되는 문제. 가장 간단한 구현 방법은, collection.Counter을 이용해서 frequency 들을 카운팅 한 뒤에, Counter의 most_common 함수를 사용하는 것이다. most_common 함수는 내부적으로 heapq.nlargest 함수를 이용한다. 시간복잡도는 O(n+klogn) 이다.
  • 사실 실용적으로는 이 정도로 충분하다. 하지만 공식 솔루션 에서는 quick select 를 이용하는 O(n) 방법을, neetcode의 솔루션 에서는 min-heap을 이용하는 O(nlogk) 방법과 카운팅소트를 이용하는 O(n) 방법도 언급하고 있긴 하다.

코드

problems/leetcode/q0347.py
"""Solution code for "LeetCode 347. Top K Frequent Elements".

- Problem link: https://leetcode.com/problems/top-k-frequent-elements/
- Solution link: http://www.teferi.net/ps/problems/leetcode/347
"""

import collections
from typing import List


class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        return [key for key, _val in collections.Counter(nums).most_common(k)]

토론

댓글을 입력하세요:
E᠎ G I A A
 
ps/problems/leetcode/347.txt · 마지막으로 수정됨: 2026/04/25 16:31 저자 teferi