leetcode/0347_top-k-frequent-elements/python3/solution.py

21 lines
699 B
Python
Raw Normal View History

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