Implementation of Priority Queue
A priority queue is an abstract data type similar to a regular queue or stack data structure in which each element additionally has a "priority" associated with it. In a priority queue, an element with high priority is served before an element with low priority.
A common misconception is that a Heap is the same as a Priority Queue, which is not true. A priority queue is an abstract data type, while a Heap is a data structure. Therefore, a Heap is not a Priority Queue, but a way to implement a Priority Queue.
There are multiple ways to implement a Priority Queue, such as array and linked list. However, these implementations only guarantee O(1) time complexity for either insertion or deletion, while the other operation will have a time complexity of O(N)O(N). On the other hand, implementing the priority queue with Heap will allow both insertion and deletion to have a time complexity of O(logN).
Priority Queue/Heap 维护了一个每次poll都是最小元素。是用complete binary tree实现。
所谓的"完全二叉树", 要满足:
除了最后一层, 所有层都排满(没有非空节点)
最后一层的所有非空节点都排在左边
一张图可以直观说明, 完全二叉树其实就是长得像这样:
A heap is a binary tree that meets the following criteria:
Is a complete binary tree;
The value of each node must be no greater than (or no less than) the value of its child nodes.
There are two kinds of heaps: Max Heap and Min Heap.
Max Heap: Each node in the Heap has a value no less than its child nodes. Therefore, the top element (root node) has the largest value in the Heap. (value of node >= values of children)
Min Heap: Each node in the Heap has a value no larger than its child nodes. Therefore, the top element (root node) has the smallest value in the Heap. (value of node <= values of children)
min heap 操作:
peek(): 返回数组的第一个元素的值,root节点总是最大/小值。time complexity: O(1)
insert(): 插入一个新的元素,总是放在数组元素的最后一个位置,然后heapifyUp,调整heap满足min heap。time complexity: O(logN)
poll(): 拿出数组的第一个元素,heap中剩下的元素要进行调整,保证heap是min heap的结构,这个过程是heapifyDown。time complexity: O(logN)
heapifyUp: 数组新增的最后一个元素与其parent进行比较, 如果新增元素的值小于其parent的值,则进行交换,递归此过程。时间复杂度是O(lgn)。
heapifyDown: 把最后一个元素放到root的位置,从root位置开始,比较root位置代表的parent与其左右children的大小,parent总是与children中元素较小的进行交换。 重复这个过程,直到大的元素不再有children。时间复杂度是O(lgn)。
build树的时候,因为有n个node,每加入一个都要heapify,所以时间复杂度是O(nlgn)
Last updated