Heap = fila de prioridade
Um Heap sempre te da o menor (min-heap) ou maior (max-heap) elemento primeiro.
Big-O:
• push — O(log n)
• pop min — O(log n)
• peek min — O(1)
Python tem heapq built-in (min-heap):
Big-O:
• push — O(log n)
• pop min — O(log n)
• peek min — O(1)
Python tem heapq built-in (min-heap):
Python
import heapqPython
def kth_largest(nums, k): heap = []
Python
for num in nums:
heapq.heappush(heap, num)
Python
if len(heap) > k:
heapq.heappop(heap)
Python
return heap[0]
Mantenha um heap de tamanho k — o topo e sempre o k-esimo maior!
Usado em: problemas top-K, merge K listas, agendamento.