20 lines
667 B
Python
20 lines
667 B
Python
from heapq import heapify, heappop
|
|
|
|
class Solution:
|
|
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
|
|
c = Counter(nums)
|
|
|
|
# Python heapq creates a min-heap but we want a max-heap built
|
|
# against counts. Tuples are comparable in Python by default so
|
|
# we can create a tuple of (count, element) to build the heap. To
|
|
# mimic a max-heap, we can just negate the counts.
|
|
heap = [(-count, val) for val, count in c.items()]
|
|
heapify(heap)
|
|
|
|
result = [None] * k
|
|
|
|
for i, _ in enumerate(result):
|
|
result[i] = heappop(heap)[1]
|
|
|
|
return result
|