Skip to main content

347. Top K Frequent Elements - LeetCode

import heapq
from collections import Counter
from itertools import chain, islice


class Solution: # O(n) / O(n)
def topKFrequent(self, nums: list[int], k: int) -> list[int]:
buckets = [[] for _ in nums]
for n, c in Counter(nums).items():
buckets[-c].append(n)
return list(islice(chain.from_iterable(buckets), k))


class Solution1: # O(nlogn) / O(n)
def topKFrequent(self, nums: list[int], k: int) -> list[int]:
heap = []
for n, c in Counter(nums).items():
heapq.heappush(heap, (-c, n))
return [heapq.heappop(heap)[1] for _ in range(k)]


class Solution2: # O(nlogn) / O(n)
def topKFrequent(self, nums: list[int], k: int) -> list[int]:
heap = []
for n, c in Counter(nums).items():
heapq.heappush(heap, (-c, n))
return [x[1] for x in heapq.nsmallest(k, heap)]


class Solution3: # O(nlogn) / O(n)
def topKFrequent(self, nums: list[int], k: int) -> list[int]:
return [n for n, _ in Counter(nums).most_common(k)]