Heap解题套路
Heap的知识
- Heap 的操作
- 从数组创建heap:使用siftDown. O(n)
- 调整heap: siftUp, siftDown (heapify) 两种, O(log n) 【可以使用递归 和 循环两种写法】
- 一般是添加一个元素,在末尾: 使用siftUp
- 去掉堆顶元素,将队尾元素放到堆顶: 使用siftDown
- 获取堆顶元素(最小值/最大值) O(1)
- heap的时间复杂度
- 证明 从数组创建heap,使用siftDown方法,时间复杂度是 O(n)
https://stackoverflow.com/questions/9755721/how-can-building-a-heap-be-on-time-complexity
- 证明 从数组创建heap,使用siftDown方法,时间复杂度是 O(n)
- heap的实际使用:java语言PriorityQueue,构造方法可以接收一个参数,lambda写比较器
- 例如:PriorityQueue
heap = new PriorityQueue<>((x, y) -> x.val - y.val); - 堆排序时,我习惯的写法是,先使用siftDown建堆,然后再依次将最大值取出放到末尾,再使用siftDown调整。所以,需要特别熟悉siftDown的操作(heapify)
- 例如:PriorityQueue