优先队列不在遵循先入先出的原则,而是分为两种情况。
1、最大优先队列,无论入队顺序如何,都是当前最大的元素优先出队。
2、最小优先队列,无论入队顺序如何,都是当前最小的元素优先出队。
这里同样会引入二叉堆的特性。
1.最大堆的堆顶是整个堆中的最大元素。
2.最小堆的堆顶是整个堆中的最小元素。
因此,可以用最大堆来实现最大优先队列。这样的话,每一次入队操作就是堆的插入操作,每一次出队操作就是删除堆顶节点。
二叉堆节点,“上浮”和“下沉”的时间复杂度都是O(nlogn),所以优先队列入队和出队的时间复杂度也是O(nlogn)!
代码实现:
/**
* @Author: subd
* @Date: 2019/8/16 7:46
*/
public class PriorityQueue {
private int[] array;
private int size;
public PriorityQueue() {
//队列出事长度为32
array = new int[32];
}
/**
* 队列扩容
*/
private void resize() {
//队列容量翻倍
int newSize = this.size * 2;
this.array = Arrays.copyOf(this.array, newSize);
}
/**
* 入队
*
* @param key 入队元素
*/
public void enQueue(int key) {
//队列长度超出范围,扩容
if (size > array.length) {
resize();
}
array[size++] = key;
upAdjust();
}
/**
* 出队
*
* @return
*/
public int deQueue() throws Exception {
if (size <= 0) {
throw new Exception("the queue is empty!");
}
//获取堆顶元素
int head = array[0];
//让最后一个元素移动到堆顶
array[0] = array[--size];
downAdjust();
return head;
}
/**
* 上浮调整
*/
private void upAdjust() {
int chldIndex = size - 1;
int parentIndex = chldIndex / 2;
//temp 保存插入的叶子节点值,用于最后的赋值
int temp = array[chldIndex];
while (chldIndex > 0 && temp > array[parentIndex]) {
//无须真正交换,单向赋值即可
array[chldIndex] = array[parentIndex];
chldIndex = parentIndex;
parentIndex = parentIndex / 2;
}
array[chldIndex] = temp;
}
/**
* 下浮调整
*/
private void downAdjust() {
//temp 保存父节点的值 用于最后的赋值
int parentIndex = 0;
int temp = array[parentIndex];
int childIndex = 1;
while (childIndex < size) {
//如果有右孩子,且右孩子大于左孩子的值,则定位到右孩子。
if (childIndex + 1 < size && array[childIndex + 1] > array[childIndex]) {
childIndex++;
}
//如果父节点大于任何一个孩子的值,直接跳出
if (temp >= array[childIndex]) {
break;
}
//无须真正交换,单向赋值即可
array[parentIndex] = array[childIndex];
parentIndex = childIndex;
childIndex = 2 * childIndex + 1;
}
array[parentIndex] = temp;
}
public static void main(String[] args) throws Exception {
PriorityQueue priorityQueue = new PriorityQueue();
priorityQueue.enQueue(3);
priorityQueue.enQueue(5);
priorityQueue.enQueue(10);
priorityQueue.enQueue(2);
priorityQueue.enQueue(7);
System.out.println("出队元素:" + priorityQueue.deQueue());
System.out.println("出队元素:" + priorityQueue.deQueue());
}
}
280

被折叠的 条评论
为什么被折叠?



