
[LeetCode] 347. Top K Frequent Elements

Counterclass Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
cnt = Counter(nums)
ans = [num for num, freq in cnt.most_common(k)]
return ans
Time:
(Counting all elements and extracting top-k frequent items)
Space:
(Frequency map plus output list)
= length of nums, = number of unique elements
freq[x] = x의 등장 횟수
Count the frequency of each element: freq[x] = number of times x appears
buckets[c] = 빈도가 c인 값들
Create buckets by frequency: buckets[c] = elements that appear c times
큰 빈도부터 내려오며 k개 모으면 끝
Traverse from the highest frequency down and collect k elements
from typing import List
from collections import Counter
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
freq = Counter(nums) # value -> count
# buckets[count] = list of values with that count
buckets = [[] for _ in range(len(nums) + 1)]
for val, cnt in freq.items():
buckets[cnt].append(val)
ans = []
# 높은 빈도부터 내려오며 채우기
for cnt in range(len(buckets) - 1, 0, -1):
for val in buckets[cnt]:
ans.append(val)
if len(ans) == k:
return ans
return ans # (문제 조건상 보통 여기 도달 안 함)
from typing import List
from collections import Counter
import heapq
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
freq = Counter(nums)
heap = [] # (count, value)
for val, cnt in freq.items():
heapq.heappush(heap, (cnt, val))
if len(heap) > k:
heapq.heappop(heap)
return [val for cnt, val in heap]