文章目录

  • Pre
  • PriorityQueue 概述
  • PriorityQueue 继承关系
  • PriorityQueue通过用数组表示的小顶堆实现
  • 时间复杂度
  • 构造函数
  • 方法
    • add()和offer()
    • element()和peek()
    • remove()和poll()
    • remove(Object o)


Pre

Java Review - ArrayList 源码解读

Java Review - LinkedList源码解读

Java Review - Queue和Stack 源码解读


PriorityQueue 概述

Java Review - Queue和Stack 源码解读以Java ArrayDeque为例讲解了Stack和Queue,还有一种特殊的队列叫做PriorityQueue,即优先队列。

优先队列的作用是能保证每次取出的元素都是队列中权值最小的

那大小关系如何评判呢? 元素大小的评判可以通过元素本身的自然顺序(natural ordering),也可以通过构造时传入的比较器


PriorityQueue 继承关系


PriorityQueue通过用数组表示的小顶堆实现

  • PriorityQueue实现了Queue接口,不允许放入null元素

  • 其通过堆实现,具体说是通过完全二叉树(complete binary tree)实现的小顶堆(任意一个非叶子节点的权值,都不大于其左右子节点的权值),也就意味着可以通过数组来作为PriorityQueue的底层实现

上图中我们给每个元素按照层序遍历的方式进行了编号, 会发现父节点和子节点的编号是有联系的,更确切的说父子节点的编号之间有如下关系:

leftNo = parentNo*2+1
rightNo = parentNo*2+2
parentNo = (nodeNo-1)/2

通过上述三个公式,可以轻易计算出某个节点的父节点以及子节点的下标。这也就是为什么可以直接用数组来存储堆的原因。


时间复杂度

  • peek()和element操作是常数时间,

  • add(), offer(), 无参数的remove()以及poll()方法的时间复杂度都是log(N)


构造函数

private static final int DEFAULT_INITIAL_CAPACITY = 11;/*** The comparator, or null if priority queue uses elements'* natural ordering.*/private final Comparator<? super E> comparator;/*** Creates a {@code PriorityQueue} with the default initial* capacity (11) that orders its elements according to their* {@linkplain Comparable natural ordering}.*/public PriorityQueue() {this(DEFAULT_INITIAL_CAPACITY, null);}/*** Creates a {@code PriorityQueue} with the specified initial* capacity that orders its elements according to their* {@linkplain Comparable natural ordering}.** @param initialCapacity the initial capacity for this priority queue* @throws IllegalArgumentException if {@code initialCapacity} is less*         than 1*/public PriorityQueue(int initialCapacity) {this(initialCapacity, null);}/*** Creates a {@code PriorityQueue} with the default initial capacity and* whose elements are ordered according to the specified comparator.** @param  comparator the comparator that will be used to order this*         priority queue.  If {@code null}, the {@linkplain Comparable*         natural ordering} of the elements will be used.* @since 1.8*/public PriorityQueue(Comparator<? super E> comparator) {this(DEFAULT_INITIAL_CAPACITY, comparator);}/*** Creates a {@code PriorityQueue} with the specified initial capacity* that orders its elements according to the specified comparator.** @param  initialCapacity the initial capacity for this priority queue* @param  comparator the comparator that will be used to order this*         priority queue.  If {@code null}, the {@linkplain Comparable*         natural ordering} of the elements will be used.* @throws IllegalArgumentException if {@code initialCapacity} is*         less than 1*/public PriorityQueue(int initialCapacity,Comparator<? super E> comparator) {// Note: This restriction of at least one is not actually needed,// but continues for 1.5 compatibilityif (initialCapacity < 1)throw new IllegalArgumentException();this.queue = new Object[initialCapacity];this.comparator = comparator;}/*** Creates a {@code PriorityQueue} containing the elements in the* specified collection.  If the specified collection is an instance of* a {@link SortedSet} or is another {@code PriorityQueue}, this* priority queue will be ordered according to the same ordering.* Otherwise, this priority queue will be ordered according to the* {@linkplain Comparable natural ordering} of its elements.** @param  c the collection whose elements are to be placed*         into this priority queue* @throws ClassCastException if elements of the specified collection*         cannot be compared to one another according to the priority*         queue's ordering* @throws NullPointerException if the specified collection or any*         of its elements are null*/@SuppressWarnings("unchecked")public PriorityQueue(Collection<? extends E> c) {if (c instanceof SortedSet<?>) {SortedSet<? extends E> ss = (SortedSet<? extends E>) c;this.comparator = (Comparator<? super E>) ss.comparator();initElementsFromCollection(ss);}else if (c instanceof PriorityQueue<?>) {PriorityQueue<? extends E> pq = (PriorityQueue<? extends E>) c;this.comparator = (Comparator<? super E>) pq.comparator();initFromPriorityQueue(pq);}else {this.comparator = null;initFromCollection(c);}}/*** Creates a {@code PriorityQueue} containing the elements in the* specified priority queue.  This priority queue will be* ordered according to the same ordering as the given priority* queue.** @param  c the priority queue whose elements are to be placed*         into this priority queue* @throws ClassCastException if elements of {@code c} cannot be*         compared to one another according to {@code c}'s*         ordering* @throws NullPointerException if the specified priority queue or any*         of its elements are null*/@SuppressWarnings("unchecked")public PriorityQueue(PriorityQueue<? extends E> c) {this.comparator = (Comparator<? super E>) c.comparator();initFromPriorityQueue(c);}/*** Creates a {@code PriorityQueue} containing the elements in the* specified sorted set.   This priority queue will be ordered* according to the same ordering as the given sorted set.** @param  c the sorted set whose elements are to be placed*         into this priority queue* @throws ClassCastException if elements of the specified sorted*         set cannot be compared to one another according to the*         sorted set's ordering* @throws NullPointerException if the specified sorted set or any*         of its elements are null*/@SuppressWarnings("unchecked")public PriorityQueue(SortedSet<? extends E> c) {this.comparator = (Comparator<? super E>) c.comparator();initElementsFromCollection(c);}

方法

add()和offer()

  • add(E e)和offer(E e)的语义相同,都是向优先队列中插入元素,只是Queue接口规定二者对插入失败时的处理不同,前者在插入失败时抛出异常,后者则会返回false。

  • 对于PriorityQueue这两个方法其实没什么差别。


新加入的元素可能会破坏小顶堆的性质,因此需要进行必要的调整。

//offer(E e)
public boolean offer(E e) {if (e == null)//不允许放入null元素throw new NullPointerException();modCount++;int i = size;if (i >= queue.length)grow(i + 1);//自动扩容size = i + 1;if (i == 0)//队列原来为空,这是插入的第一个元素queue[0] = e;elsesiftUp(i, e);//调整return true;
}

如上,扩容函数grow()类似于ArrayList里的grow()函数,就是再申请一个更大的数组,并将原数组的元素复制过去 。

需要注意的是siftUp(int k, E x)方法,该方法用于插入元素x并维持堆的特性。

//siftUp()
private void siftUp(int k, E x) {while (k > 0) {int parent = (k - 1) >>> 1;//parentNo = (nodeNo-1)/2Object e = queue[parent];if (comparator.compare(x, (E) e) >= 0)//调用比较器的比较方法break;queue[k] = e;k = parent;}queue[k] = x;
}

新加入的元素x可能会破坏小顶堆的性质,因此需要进行调整。调整的过程为 : 从k指定的位置开始,将x逐层与当前点的parent进行比较并交换,直到满足x >= queue[parent]为止。注意这里的比较可以是元素的自然顺序,也可以是依靠比较器的顺序。


element()和peek()

//peek()
public E peek() {if (size == 0)return null;return (E) queue[0];//0下标处的那个元素就是最小的那个
}
  • element()和peek()的语义完全相同,都是获取但不删除队首元素,也就是队列中权值最小的那个元素,二者唯一的区别是当方法失败时前者抛出异常,后者返回null。

  • 根据小顶堆的性质,堆顶那个元素就是全局最小的那个;

  • 由于堆用数组表示,根据下标关系,0下标处的那个元素既是堆顶元素。所以直接返回数组0下标处的那个元素即可


remove()和poll()

  • remove()和poll()方法的语义也完全相同,都是获取并删除队首元素,区别是当方法失败时前者抛出异常,后者返回null。

  • 由于删除操作会改变队列的结构,为维护小顶堆的性质,需要进行必要的调整。

public E poll() {if (size == 0)return null;int s = --size;modCount++;E result = (E) queue[0];//0下标处的那个元素就是最小的那个E x = (E) queue[s];queue[s] = null;if (s != 0)siftDown(0, x);//调整return result;
}
  • 先记录0下标处的元素,并用最后一个元素替换0下标位置的元素,之后调用siftDown()方法对堆进行调整,最后返回原来0下标处的那个元素(也就是最小的那个元素)。

  • 重点是siftDown(int k, E x)方法,该方法的作用是从k指定的位置开始,将x逐层向下与当前点的左右孩子中较小的那个交换,直到x小于或等于左右孩子中的任何一个为止

//siftDown()
private void siftDown(int k, E x) {int half = size >>> 1;while (k < half) {//首先找到左右孩子中较小的那个,记录到c里,并用child记录其下标int child = (k << 1) + 1;//leftNo = parentNo*2+1Object c = queue[child];int right = child + 1;if (right < size &&comparator.compare((E) c, (E) queue[right]) > 0)c = queue[child = right];if (comparator.compare(x, (E) c) <= 0)break;queue[k] = c;//然后用c取代原来的值k = child;}queue[k] = x;
}


remove(Object o)

  • remove(Object o)方法用于删除队列中跟o相等的某一个元素(如果有多个相等,只删除一个),该方法不是Queue接口内的方法,而是Collection接口的方法。由于删除操作会改变队列结构,所以要进行调整;

  • 又由于删除元素的位置可能是任意的,所以调整过程比其它函数稍加繁琐。具体来说,remove(Object o)可以分为2种情况: 1. 删除的是最后一个元素。直接删除即可,不需要调整。2. 删除的不是最后一个元素,从删除点开始以最后一个元素为参照调用一次siftDown()即可.

//remove(Object o)
public boolean remove(Object o) {//通过遍历数组的方式找到第一个满足o.equals(queue[i])元素的下标int i = indexOf(o);if (i == -1)return false;int s = --size;if (s == i) //情况1queue[i] = null;else {E moved = (E) queue[s];queue[s] = null;siftDown(i, moved);//情况2......}return true;
}

Java Review - PriorityQueue源码解读相关推荐

  1. Java Review - LinkedList源码解读

    文章目录 Pre 概述 底层数据结构-双向链表 源码解析 构造函数 方法源码分析 getFirst() getLast() remove相关方法 remove(e) remove(index) rem ...

  2. Java Review - ArrayList 源码解读

    文章目录 概述 方法的执行效率 源码剖析 底层数据结构 -数组 构造函数 自动扩容机制 set() get add()/addAll() remove() trimToSize() indexOf() ...

  3. java基本集合源码解读-JDK8/11

    文章目录 前言 详尽的debugger底层查看源码配置 一.集合体系图 二.List类集合 2.1.1 ArrayList 2.1.2ArrayList底层源码分析 结论: 2.1.3 使用Array ...

  4. java Map toString() 源码解读测试

    1. 编写一个单元测试类 @Testpublic void tt() {Map<Object, Object> map = new HashMap<>();map.put(&q ...

  5. Java Review - Queue和Stack 源码解读

    文章目录 Pre 概述 Queue Deque ArrayDeque 一览 构造函数 属性 方法 addFirst() addLast() pollFirst() pollLast() peekFir ...

  6. Java Review - LinkedHashMap LinkedHashSet 源码解读

    文章目录 Pre 概述 数据结构 类继承关系 构造函数 方法 get() put() remove() LinkedHashSet 使用案例 - FIFO策略缓存 Pre Java Review - ...

  7. Java Review - HashMap HashSet 源码解读

    文章目录 概述 HashMap结构图 构造函数 重点方法源码解读 (1.7) put() get() remove() 1.8版本 HashMap put resize() 扩容 get HashSe ...

  8. aqs java 简书,Java AQS源码解读

    1.先聊点别的 说实话,关于AQS的设计理念.实现.使用,我有打算写过一篇技术文章,但是在写完初稿后,发现掌握的还是模模糊糊的,模棱两可. 痛定思痛,脚踏实地重新再来一遍.这次以 Java 8源码为基 ...

  9. hystrix 源码 线程池隔离_“池”的思想:从java线程池到数据库连接池的源码解读(1)...

    一. java线程池 带着问题: 线程是什么时候被创建的? 线程会一直循环取任务任务吗?怎么做的? 线程取不到任务会怎么样? 线程会被Runnable和Callable的异常干掉吗? 线程怎么干掉自己 ...

最新文章

  1. PyTorch中AdaptiveAvgPool函数总结
  2. 如何在 Outlook 2003、Outlook 2007 中管理pst 文件
  3. Codeforces round 396(Div. 2) 题解
  4. 安卓学习随笔 -- 自定义标题栏
  5. 简单 fibonacci 函数
  6. mybatis如何处理参数
  7. 双系统win+ubuntu14.04使用360随身wifi 3代
  8. 【十五分钟Talkshow】如何理解并优化.NET应用程序对内存的使用
  9. 计算机视觉算法与应用汇总
  10. xodo pdf android,Xodo PDF查看器和编辑器「Xodo PDF Viewer Editor」
  11. 紧急求助,CSDN帮忙下载HP惠普280G1增霸卡7.0UEFI版硬盘保护卡还原卡驱动光盘
  12. 有没有可以搜索python程序的软件-有哪些可以搜Python题答案的APP
  13. 一根网线让两台笔记本对拷文件
  14. 阿里云服务器购买流程及连接测试(学习笔记)
  15. python输入三门课程成绩_编一程序,从键盘输入学生的三门课程成绩,求其总成绩、平均成绩和总成绩除3的余值...
  16. 关键词提取——有监督方法
  17. 【攀爬者系列】北冥神功之归并算法(十七式)
  18. PERL-5.26.1安装教程(LINUX系统)
  19. Adversarial Semantic Hallucination for Domain Generalized Semantic Segmentation
  20. 机器学习----纯手撸线性回归代码

热门文章

  1. LeanCloud数据更新不同步问题
  2. encoder decoder 模型理解
  3. 域用户组成员 导出_隐私安全,黑客利用Mimikatz提取Windows用户凭证
  4. oracle sql练习_数据分析之学习SQL
  5. python写自动答题脚本_问卷星的自动答题脚本
  6. Leetcode 91. 解码方法 (每日一题 20211013)
  7. 强化学习Reinforcement Learning
  8. 论文笔记:Matrix Completion in the Unit Hypercube via Structured Matrix Factorization
  9. MATLAB基本操作(一):MATLAB中变量的文件存储
  10. 新手入门深度学习 | 2-3:文本数据建模流程示例