优先级队列是基于优先级堆的,优先级队列的元素是基于它们的自然顺序有序排列的。不允许有空元素,默认为最小堆。
声明定义:
PriorityQueue<T> pq=new PriorityQueue<T>();从小到达排序
PriorityQueue<T> pq=new PriorityQueue<T>(Collections.reverse());从大到小排序
主要函数:
add(E e): boolean 向队列添加指定元素, as specified by Collection.add(E) e是要添加的元素
offer(E e):boolean 向队列添加指定元素 ,as specified by Queue.offer(E)
peek( ): return 队首元素
remove(Object o): boolean 删除指定元素
toArray():return an array,包含队列所有元素
contains(Object o):boolean 是否包含指定元素
size():return元素个数
poll():返回且删除队首元素
clear():删除队列所有元素
应用实例:
LeetCode 239:https://blog.youkuaiyun.com/liuwenyou/article/details/100534121
API链接:
priorityQueue API链接:https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html

本文深入探讨了优先级队列的原理与应用,基于优先级堆实现,元素按自然顺序排列,提供从小到大或从大到小排序方式。文章详细介绍了主要函数如add、offer、peek等,并通过LeetCode题目实例进行讲解。
5852

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



