当前位置:   article > 正文

(Java)数据结构---优先级队列(PriorityQueue)_javapriorityqueue)

javapriorityqueue)

目录

概念

PriorityQueue的使用

小试牛刀(最小k个数) 

堆的介绍

优先级队列的模拟实现

堆的应用 

Top-k问题


概念

优先级队列是一种先进先出(FIFO)的数据结构,与队列不同的是,操作的数据带有优先级,通俗的讲就是可以比较大小,在出队列的时候往往需要优先级最高或者最低的元素先出队列,这种数据结构就是优先级队列(PriorityQueue)

PriorityQueue的使用

构造方法 

这里只介绍三种常用的构造方法 

构造方法说明
PriorityQueue()不带参数,默认容量为11
PriorityQueue(int initialCapacity)参数为初始容量,该初始容量不能小于1
PriorityQueue(Collection<? extends E> c)参数为一个集合

代码展示:

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.PriorityQueue;
  4. public class TestPriorityQueue {
  5. public static void main(String[] args) {
  6. PriorityQueue<Integer> p1 = new PriorityQueue<>(); //容量默认为11
  7. PriorityQueue<Integer> p2 = new PriorityQueue<>(10); //参数为初始容量
  8. List<Integer> list = new ArrayList<>();
  9. list.add(0);
  10. list.add(1);
  11. list.add(2);
  12. PriorityQueue<Integer> p3 = new PriorityQueue<>(list); //使用集合list作为参数构造优先
  13. // 级队列
  14. }
  15. }

常用方法 

方法说明
boolean offer(E e)插入元素e,返回是否插入成功,e为null,会抛异常
E peek()获取堆(后面介绍堆)顶元素,如果队列为空,返回null
E poll()删除堆顶元素并返回,如果队列为空,返回null
int size()获取有效元素个数
void clear()清空队列
boolean isEmpty()判断队列是否为空

offer方法的测试 

  1. PriorityQueue<Integer> p = new PriorityQueue<>();
  2. p.offer(1);
  3. p.offer(2);
  4. p.offer(3);
  5. System.out.println(p.size());
  6. p.offer(null);

打印结果:

1,2,3都正常插入,但是插入null的时候,报了NullPointerException空指针异常 

peek与poll方法的测试 

  1. PriorityQueue<Integer> p = new PriorityQueue<>();
  2. p.offer(1);
  3. p.offer(2);
  4. p.offer(3);
  5. System.out.println(p.peek());
  6. System.out.println(p.poll());
  7. System.out.println(p.size());
  8. p.clear();
  9. System.out.println(p.peek());
  10. System.out.println(p.poll());

打印结果:

默认是小堆,所以堆顶元素是1,获取到1,在删除1,剩余元素个数为两个,当队列为空的时候,这两个方法都返回null 

size,isEmpty,clear方法的测试 

  1. PriorityQueue<Integer> p = new PriorityQueue<>();
  2. p.offer(1);
  3. p.offer(2);
  4. p.offer(3);
  5. System.out.println(p.size());
  6. System.out.println(p.isEmpty());
  7. p.clear();
  8. System.out.println(p.isEmpty());

打印结果:

打印元素个数为3,所以不为空输出false,清空后,队列为空,输出true 

注意事项 

  • PriorityQueue中存放的元素必须能比较大小,不能比较大小的对象不能插入,会抛出ClassCastException异常 

例如:向优先级队列中插入两个学生类型的数据

  1. class Student {
  2. private String name;
  3. private int age;
  4. public Student(String name, int age) {
  5. this.name = name;
  6. this.age = age;
  7. }
  8. }
  9. public class Test {
  10. public static void main(String[] args) {
  11. Student s1 = new Student("张三",25);
  12. Student s2 = new Student("李四",30);
  13. PriorityQueue<Student> p = new PriorityQueue();
  14. p.offer(s1);
  15. p.offer(s2);
  16. }
  17. }

结果:报了类型转换异常的错误,因为student类型不能直接比较大小

如果想比较两个自定类型的大小,请参考Java中对象的比较这篇文章

  • 不能插入null对象,否则会抛NullPointerException异常
  • 内部可以自动扩容
  • PriorityQueue底层使用堆数据结构
  • PriorityQueue默认是小堆,如果想要创建大堆可以使用如下方式创建:
  1. PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
  2. @Override
  3. public int compare(Integer o1, Integer o2) {
  4. return o2-o1;
  5. }
  6. });

注意:o2-o1是创建大堆,o1-o2是创建小堆 

PriorityQueue的扩容方式 

以下是JDK1.8中扩容的方式:

说明:

  • 如果容量小于64,按照oldCapacity的2倍扩容
  • 如果容量大于等于64,按照oldCapacity的1.5倍扩容
  • 如果容量超过MAX_ARRAY_SIZE,按照MAX_ARRAY_SIZE扩容 

小试牛刀(最小k个数) 

题目连接:最小k个数

方法:创建一个优先级队列,奖数组中的元素依次放入该优先级队列中,在依次从该优先级队列取出k个即可

  1. class Solution {
  2. public int[] smallestK(int[] arr, int k) {
  3. int[] ret = new int[k];
  4. if(k == 0 || arr.length==0){
  5. return ret;
  6. }
  7. PriorityQueue<Integer> p = new PriorityQueue<>(arr.length);
  8. for(int i = 0;i < arr.length;i++){
  9. p.offer(arr[i]);
  10. }
  11. for(int i = 0;i < k;i++){
  12. ret[i] = p.poll();
  13. }
  14. return ret;
  15. }
  16. }

堆的介绍

JDK1.8中PriorityQueue底层采用了堆数据结构,堆其实就是对完全二叉树的元素作出了一些调整

所谓堆就是将一组数据按照完全二叉树的顺序存储方式存储,保证每一个根结点元素大于它的孩子结点的元素(大根堆)或者小于它的孩子结点的元素(小根堆)

堆的性质

  • 堆中某个结点的值总是不大于或着不小于其父节点的值
  • 堆是一颗完全二叉树

堆的创建 

此处我们创建小堆,以21,15,19,17,18,23,25为例

发现上述序列根的左右子树都已经满足小堆的特性,故只需要将根结点向下调整即可 

向下调整的过程:

1. 用parent标记要被调整的结点,child标记parent的左孩子

2. 如果左孩子存在,即child<size,size为序列元素的个数,进行以下操作,直到左孩子不存在

  • 判断parent右孩子是否存在,如果存在让child标记两个孩子最小的孩子
  • 如果parent小于child,则将parent与child标记的元素交换位置,如果parent大于child,说明此时已经满足小堆的特性
  • 让parent=child,child=parent*2+1,循环步骤2,直到不满足步骤2的条件

代码展示:

  1. public void shiftDown(int[] array,int parent){
  2. int child = parent*2+1;
  3. int size = array.length;
  4. while(child < size){
  5. if(child+1<size && array[child]>array[child+1]){
  6. child = child+1;
  7. }
  8. if(array[parent] > array[child]){
  9. swap(array,parent,child);
  10. parent = child;
  11. child = parent*2+1;
  12. }else {
  13. break;
  14. }
  15. }
  16. }

注意:在调整以parent为根的二叉树时,必须满足parent的左右子树满足堆的特性,此时才能向下调整parent

时间复杂度分析:最坏情况从根比到叶子,比较的次数为二叉树的高度,故时间复杂度为O(log2N)

那么对于普通的序列如1,5,3,8,7,6,即根节点的左右子树不满足大堆的特性,该如何调整?

方法:从倒数第一个非叶子结点开始调整,直到调整到根

代码展示:

  1. public void createHeap(int[] array){
  2. int root = (array.length-2)>>1;
  3. for(;root>=0;root--){
  4. shiftDown(array,root);
  5. }
  6. }

创建堆的时间复杂度 

故建堆的时间复杂度为O(N)

堆的插入 

堆的插入分为两步:

  • 将元素插入队列尾部,如果空间不够需要扩容
  • 将新插入的结点向上调整,直到满足堆的特性 

例如:给大堆8,7,6,5,1,3插入9

代码展示:

  1. public void shiftUp(int[] array,int child){
  2. int parent = (child-1)/2;
  3. while(child > 0){
  4. if(array[child] < array[parent]){
  5. break;
  6. }else {
  7. swap(array,parent,child);
  8. child = parent;
  9. parent = (child-1)/2;
  10. }
  11. }
  12. }

堆的删除 

堆删除的是堆顶元素

删除步骤:

  • 交换堆顶与堆最后一个元素的位置
  • 将堆中的有效元素个数减少一个
  • 将堆顶元素向下调整 

代码展示:

  1. public int poll(){
  2. int oldVal = array[0];
  3. array[0] = array[array.length-1];
  4. size--;
  5. shiftDown(array,0);
  6. return oldVal;
  7. }

优先级队列的模拟实现

此处用小堆实现优先级队列,并且队列中保存的元素为Integer类型

准备工作包括:构造方法,向上调整,向下调整,交换 

  1. public class MyPriorityQueue {
  2. Integer[] array;
  3. int size;
  4. public MyPriorityQueue(){
  5. array = new Integer[11];
  6. size = 0;
  7. }
  8. public MyPriorityQueue(int initCapacity){
  9. if(initCapacity < 1){
  10. throw new IllegalArgumentException("初始容量小于1");
  11. }
  12. array = new Integer[initCapacity];
  13. size = 0;
  14. }
  15. public MyPriorityQueue(Integer[] arr){
  16. array = new Integer[arr.length];
  17. for(int i = 0;i < arr.length;i++){
  18. array[i] = arr[i];
  19. }
  20. size = arr.length;
  21. int lastLeafParent = (size-2)/2;
  22. for(int root = lastLeafParent;root >= 0;root--){
  23. shiftDown(root);
  24. }
  25. }
  26. public void shiftDown(int parent){
  27. int child = parent*2+1;
  28. while(child < size){
  29. if(child+1<size && array[child+1]<array[child]){
  30. child = child+1;
  31. }
  32. if(array[parent] > array[child]){
  33. swap(parent,child);
  34. parent = child;
  35. child = parent*2+1;
  36. }else {
  37. return;
  38. }
  39. }
  40. }
  41. public void shiftUp(int child){
  42. int parent = (child-1)/2;
  43. while(child > 0){
  44. if(array[child] < array[parent]){
  45. swap(child,parent);
  46. child = parent;
  47. parent = (child-1)/2;
  48. }else {
  49. return;
  50. }
  51. }
  52. }
  53. public void swap(int a,int b){
  54. int t = array[a];
  55. array[a] = array[b];
  56. array[b] = t;
  57. }
  58. }

插入

  1. public boolean offer(Integer e){
  2. if(e == null){
  3. throw new NullPointerException("插入的元素为null");
  4. }
  5. ensureCapacity();
  6. array[size++] = e;
  7. shiftUp(size-1);
  8. return true;
  9. }
  10. private void ensureCapacity(){
  11. if(array.length == size){
  12. int newCapacity = array.length*2;
  13. array = Arrays.copyOf(array,newCapacity);
  14. }
  15. }

注意:插入前需要判断是否扩容,此处扩容按照2倍方式扩容

删除 

  1. public Integer poll(){
  2. if(isEmpty()){
  3. return null;
  4. }
  5. Integer ret = array[0];
  6. swap(0,size-1);
  7. shiftDown(0);
  8. return ret;
  9. }

获取堆顶元素

  1. public Integer peek(){
  2. if(isEmpty()){
  3. return null;
  4. }
  5. Integer ret = array[0];
  6. return ret;
  7. }

获取有效元素个数

  1. public int size(){
  2. return size;
  3. }

判空

  1. public boolean isEmpty(){
  2. return size==0;
  3. }

清空

  1. public void clear(){
  2. size = 0;
  3. }

堆的应用 

Top-k问题

即求数据中前k个最大或者最小元素,一般情况下数据量都会比较大

如果数据量大使用排序那种方法就不可取了,那么如何解决呢?

1. 使用数据中前k个数据建堆

  • 求前k个最大,建小堆
  • 求前k个最小,建大堆

2. 用剩余的元素依次与堆顶元素比较

  • 求前k个最大,若比堆顶元素大,则替换小堆堆顶元素
  • 求前k个最小,若比堆顶元素小,则替换大堆堆顶元素 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/277129
推荐阅读
相关标签
  

闽ICP备14008679号