Top K Frequent Elements
Min-Heap
Problem
Thought Process
Solution
from heapq import *
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
freq = {}
heap = []
for i in nums:
if i not in freq:
freq[i] = 0
freq[i]+=1
for num, count in freq.items():
heappush(heap, (count, num))
if len(heap) > k:
heappop(heap)
res = []
for i in range(len(heap)):
res.append(heap[i][1])
return res
Key Points
Time Complexity
Last updated