一.优先队列的定义及其应用:

1.定义:

PriorityQueue翻译过来是优先队列,是队列中的一种特殊队列。PriorityQueue里的元素是有序的,默认情况下是单调增,可以通过传入Comparator根据自己的需求来更改。

在概念上,它是一个有序的二叉树,这种顺序的规则是(默认情况下),每个节点的值都比它的孩子节点的值小。最小堆。
在实现上,它使用数组来存储。因为该最小堆的是完全二叉树,所以按照每层从左向右的顺序存储。

2.应用:

数据的操作为每次需要取最大值或最小值时。

二.优先队列的继承关系:

1.继承关系:

image.png
PriorityQueue属于集合框架下的类。它具有集合的特点,所以集合中的方法它能够使用。PriorityQueue继承自AbstractQueue,不允许插入null元素。
PriorityQueue继承自Queue, 所以在使用上 也继承了Queue的 offer()与poll()。

2.API:

基于优先级堆的无限优先级[queue](https://blog.csdn.net/qq_22596931/java/util/Queue.html) 。 优先级队列的元素根据它们的有序[natural ordering](https://blog.csdn.net/qq_22596931/java/lang/Comparable.html) ,或由一个[Comparator](https://blog.csdn.net/qq_22596931/java/util/Comparator.html)在队列构造的时候提供,这取决于所使用的构造方法。 优先队列不允许null元素。 依靠自然排序的优先级队列也不允许插入不可比较的对象(这样做可能导致ClassCastException )。
该队列的头部是相对于指定顺序的最小元素。 如果多个元素被绑定到最小值,那么头就是这些元素之一 - 关系被任意破坏。 队列检索操作poll , remove , peek和element访问在队列的头部的元件。

类及其迭代器实现[Collection](https://blog.csdn.net/qq_22596931/java/util/Collection.html)和[Iterator](https://blog.csdn.net/qq_22596931/java/util/Iterator.html)接口的所有可选方法。 方法[iterator()](https://blog.csdn.net/qq_22596931/java/util/PriorityQueue.html#iterator--)中提供的迭代器不能保证以任何特定顺序遍历优先级队列的元素。 如果需要有序遍历,请考虑使用Arrays.sort(pq.toArray()) 。
请注意,此实现不同步。 如果任何线程修改队列,多线程不应同时访问PriorityQueue实例。 而是使用线程安全的[PriorityBlockingQueue](https://blog.csdn.net/qq_22596931/java/util/concurrent/PriorityBlockingQueue.html)类。
实现注意事项:此实现提供了O(日志(n))的时间入队和出队方法( offer , poll , remove()和add ); remove(Object)和contains(Object)方法的线性时间; 和恒定时间检索方法( peek , element和size )。

三.优先队列的相关源码:

PriorityQueue内部实现方式为数组,因此优先队列的私有化参数有:

  1. private static final long serialVersionUID = -7720805057305804111L;
  2. private static final int DEFAULT_INITIAL_CAPACITY = 11;//默认容量11
  3. transient Object[] queue;//内置的数组
  4. private int size = 0;//参数规模
  5. private final Comparator<? super E> comparator;//比较器
  6. transient int modCount = 0;

1.构造方法:

PriorityQueue的构造方法方法有:

image.png

  1. public PriorityQueue() {
  2. this(DEFAULT_INITIAL_CAPACITY, null);
  3. }
  4. /**
  5. * Creates a {@code PriorityQueue} with the specified initial
  6. * capacity that orders its elements according to their
  7. * {@linkplain Comparable natural ordering}.
  8. *
  9. * @param initialCapacity the initial capacity for this priority queue
  10. * @throws IllegalArgumentException if {@code initialCapacity} is less
  11. * than 1
  12. */
  13. public PriorityQueue(int initialCapacity) {
  14. this(initialCapacity, null);
  15. }
  16. /**
  17. * Creates a {@code PriorityQueue} with the default initial capacity and
  18. * whose elements are ordered according to the specified comparator.
  19. *
  20. * @param comparator the comparator that will be used to order this
  21. * priority queue. If {@code null}, the {@linkplain Comparable
  22. * natural ordering} of the elements will be used.
  23. * @since 1.8
  24. */
  25. public PriorityQueue(Comparator<? super E> comparator) {
  26. this(DEFAULT_INITIAL_CAPACITY, comparator);
  27. }
  28. /**
  29. * Creates a {@code PriorityQueue} with the specified initial capacity
  30. * that orders its elements according to the specified comparator.
  31. *
  32. * @param initialCapacity the initial capacity for this priority queue
  33. * @param comparator the comparator that will be used to order this
  34. * priority queue. If {@code null}, the {@linkplain Comparable
  35. * natural ordering} of the elements will be used.
  36. * @throws IllegalArgumentException if {@code initialCapacity} is
  37. * less than 1
  38. */
  39. public PriorityQueue(int initialCapacity,
  40. Comparator<? super E> comparator) {
  41. // Note: This restriction of at least one is not actually needed,
  42. // but continues for 1.5 compatibility
  43. if (initialCapacity < 1)
  44. throw new IllegalArgumentException();
  45. this.queue = new Object[initialCapacity];
  46. this.comparator = comparator;
  47. }
  48. /**
  49. * Creates a {@code PriorityQueue} containing the elements in the
  50. * specified collection. If the specified collection is an instance of
  51. * a {@link SortedSet} or is another {@code PriorityQueue}, this
  52. * priority queue will be ordered according to the same ordering.
  53. * Otherwise, this priority queue will be ordered according to the
  54. * {@linkplain Comparable natural ordering} of its elements.
  55. *
  56. * @param c the collection whose elements are to be placed
  57. * into this priority queue
  58. * @throws ClassCastException if elements of the specified collection
  59. * cannot be compared to one another according to the priority
  60. * queue's ordering
  61. * @throws NullPointerException if the specified collection or any
  62. * of its elements are null
  63. */
  64. @SuppressWarnings("unchecked")
  65. public PriorityQueue(Collection<? extends E> c) {
  66. if (c instanceof SortedSet<?>) {
  67. SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
  68. this.comparator = (Comparator<? super E>) ss.comparator();
  69. initElementsFromCollection(ss);
  70. }
  71. else if (c instanceof PriorityQueue<?>) {
  72. PriorityQueue<? extends E> pq = (PriorityQueue<? extends E>) c;
  73. this.comparator = (Comparator<? super E>) pq.comparator();
  74. initFromPriorityQueue(pq);
  75. }
  76. else {
  77. this.comparator = null;
  78. initFromCollection(c);
  79. }
  80. }
  81. /**
  82. * Creates a {@code PriorityQueue} containing the elements in the
  83. * specified priority queue. This priority queue will be
  84. * ordered according to the same ordering as the given priority
  85. * queue.
  86. *
  87. * @param c the priority queue whose elements are to be placed
  88. * into this priority queue
  89. * @throws ClassCastException if elements of {@code c} cannot be
  90. * compared to one another according to {@code c}'s
  91. * ordering
  92. * @throws NullPointerException if the specified priority queue or any
  93. * of its elements are null
  94. */
  95. @SuppressWarnings("unchecked")
  96. public PriorityQueue(PriorityQueue<? extends E> c) {
  97. this.comparator = (Comparator<? super E>) c.comparator();
  98. initFromPriorityQueue(c);
  99. }
  100. /**
  101. * Creates a {@code PriorityQueue} containing the elements in the
  102. * specified sorted set. This priority queue will be ordered
  103. * according to the same ordering as the given sorted set.
  104. *
  105. * @param c the sorted set whose elements are to be placed
  106. * into this priority queue
  107. * @throws ClassCastException if elements of the specified sorted
  108. * set cannot be compared to one another according to the
  109. * sorted set's ordering
  110. * @throws NullPointerException if the specified sorted set or any
  111. * of its elements are null
  112. */
  113. @SuppressWarnings("unchecked")
  114. public PriorityQueue(SortedSet<? extends E> c) {
  115. this.comparator = (Comparator<? super E>) c.comparator();
  116. initElementsFromCollection(c);
  117. }

2.常用方法:

image.png
image.png

3.使用示例:

leetcode23题:合并K个升序链表

  1. class Solution {
  2. public ListNode mergeKLists(ListNode[] lists) {
  3. //lamboda表达式初始化优先队列
  4. PriorityQueue<ListNode> q = new PriorityQueue<>((x,y)->x.val-y.val);
  5. for(ListNode node : lists){
  6. if(node!=null){
  7. q.add(node);
  8. }
  9. }
  10. ListNode head = new ListNode(0);
  11. ListNode tail = head;
  12. while(!q.isEmpty()){
  13. tail.next = q.poll();
  14. tail = tail.next;
  15. if (tail.next != null){
  16. q.add(tail.next);
  17. }
  18. }
  19. return head.next;
  20. }
  21. }
  1. public ListNode mergeKLists(ListNode[] lists) {
  2. //内部类
  3. Queue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>() {
  4. @Override
  5. public int compare(ListNode o1, ListNode o2) {
  6. return o1.val-o2.val;
  7. }
  8. });
  9. for (ListNode list : lists) {
  10. if (list != null){
  11. queue.offer(list);
  12. }
  13. }
  14. ListNode dummyHead = new ListNode(0);
  15. ListNode tail = dummyHead;
  16. while(!queue.isEmpty()){
  17. ListNode minNode = queue.poll();
  18. tail.next=minNode;
  19. tail = minNode;
  20. if (minNode.next!=null){
  21. queue.offer(minNode.next);
  22. }
  23. }
  24. return dummyHead.next;
  25. }