2022-04-21 09:42:46 +00:00
|
|
|
from collections import Counter
|
2022-04-09 17:45:20 +00:00
|
|
|
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
|