347. Top K Frequent Elements
Find the k most frequent elements in an array.
Approach: Min-Heap
Algorithm:
- Count the frequency of each element in the array.
- Use a min-heap to keep track of the k most frequent elements.
- Iterate through the frequency map and add elements to the heap, maintaining its size at k.
- Return the elements in the heap.
from collections import Counter
import heapq
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = Counter(nums)
heap = []
for num, freq in count.items():
heapq.heappush(heap, (freq, num))
if len(heap) > k:
heapq.heappop(heap)
return [num for _, num in heap]- Time: — where is the number of elements in the array, and we perform at most heap operations, each taking time.
- Space: — the frequency map holds up to entries and the heap holds up to elements.
Last updated on