堆, 优先队列,可以用来排序,计算top k问题
heap property:
In a max-heap, the max-heap property is that for every node i other than the root, A[parent([i)] >= A[i]. That is, the value of the node is at most the value of its parent. Thus the largest element is stored at the root.
binary heap: like a complete binary tree.
interface:
1. maxHeapify(A, i, n): 维护堆性质。不变量: 执行前 (1) i的left, right subtrees are already max heaps. (2) the value of node i may be smaller than those of its left and right children. 执行后: the tree rooted at node i is max heap. (n 用来判断left(i), right(i) 是否还是有效的index) O(lgn)
2. buildMaxHeap: for nodes n/2 to n, are already 1-node heaps. Iterate i from n/2 down to 1, call maxHeapify(A, i, n) Time complexity: O(n)
HeapSort(A, n): first create a max heap, iterate i from n to 1: swap(A[1], A[i]) (currently A[1] is the largest ele, put it to A[i]), then call maxHeapify(A, 1, i - 1). O(nlgn)
Use max heap to implement a priority queue.
Maximum(A): return the largest element. O(1) return A[1].
Extract-Max(A): remove and return the largest element. max = A[1], swap(A[1], A[n]), maxHeapify(A, 1, n-1), return max
IncreaseKey(A, k, x): suppose x >= A[k]. A[k] = x, only need to adjust elements from parent[k] along to 1 (since children of k already satisfy max-heap property). while k > 1: if(A[parent(k)] < A[k]) swap(A[parent(k)], A[k]); k = parent(k).
即只需要调整从k到1那条路径上的值即可。
Insert(A, key, n): A.heapSize = A. heapSize + 1; A[n] = Integer.MIN_VALUE; IncreaseKey(A, A.heapSize, key) O(lgn)