Heap = cây nhị phân với invariant: parent <= (min-heap) hoặc >= (max-heap) các child.
Thao tác:
- Push: O(log n)
- Pop (top): O(log n)
- Peek (top): O(1)
- Heapify mảng: O(n)
Khi nào dùng Heap thay sort?
- Cần top K phần tử (K << n): heap K phần tử cho O(n log k) tốt hơn O(n log n) sort
- Cần streaming — phần tử đến liên tục, không có toàn bộ trước
- Cần k-way merge — merge K sorted lists
- Cần scheduling — pick highest-priority task next
Ví dụ:
ts
// Top 3 phần tử lớn nhất
const heap = new MinHeap<number>()
for (const x of nums) {
heap.push(x)
if (heap.size() > 3) heap.pop() // bỏ phần tử nhỏ nhất
}
return heap.toArray() // 3 phần tử lớn nhấtJS không có Heap built-in — cần implement hoặc dùng lib.
Python có heapq, C++ có priority_queue.
Heap is a binary tree with parent ≤/≥ children invariant.
- Push/Pop O(log n), Peek O(1), Heapify O(n).
- Use when need top-K (n log k > n log n if k<<n), streaming data, k-way merge, or priority-based scheduling.