当前位置: 首页 > news >正文

Java优先队列的使用

1. 优先队列的定义

PriorityQueue继承了Queue接口,底层默认是一个小根堆。

PriorityQueue<Integer> queue=new PriorityQueue<>();

2. 常用方法

方法描述
boolean offer(E e)入队列
E poll()出队列
E peek()得到队首元素

int size()

返回集合中的元素个数 

3. 自定义优先队列比较

PriorityQueue插入的元素不能是null 并且元素之间必须能够进行比较。

3.1 自定义比较器

// 定义的某个要比较类型的比较器
class IntegerComparator implements Comparator<Integer>{@Overridepublic int compare(Integer o1,Integer o2){// 如果第二个元素-第一个元素就是大根堆的实现方式,反之则为小根堆的创建方式,可以从源码去了解return o2-o1;}
}
public class TestDemo{public static void main(String[] args){PriorityQueue<Integer> maxHeap=new PriorityQueue<>(IntegerComparator);}
}

3.2 使用匿名内部类

// 定义的某个要比较类型的比较器
class IntegerComparator implements Comparator<Integer>{@Overridepublic int compare(Integer o1,Integer o2){// 如果第二个元素-第一个元素就是大根堆的实现方式,反之则为小根堆的创建方式,可以从源码去了解return o2-o1;}
}
public class TestDemo{public static void main(String[] args){PriorityQueue<Integer> maxHeap=new PriorityQueue<>(IntegerComparator);}
}

3.3 使用Lamda表达式

PriorityQueue<Integer> pq=new PriorityQueue<>((o1,o2)-> Integer.compare(o2,o1));

4. 补充堆排序的实现

class Solution {public int findKthLargest(int[] nums, int k) {int heapSize = nums.length;buildMaxHeap(nums, heapSize);for (int i = nums.length - 1; i >= nums.length - k + 1; --i) {swap(nums, 0, i);--heapSize;maxHeapify(nums, 0, heapSize);}return nums[0];}public void buildMaxHeap(int[] a, int heapSize) {for (int i = heapSize / 2; i >= 0; --i) {maxHeapify(a, i, heapSize);} }public void maxHeapify(int[] a, int i, int heapSize) {int l = i * 2 + 1, r = i * 2 + 2, largest = i;if (l < heapSize && a[l] > a[largest]) {largest = l;} if (r < heapSize && a[r] > a[largest]) {largest = r;}if (largest != i) {swap(a, i, largest);maxHeapify(a, largest, heapSize);}}public void swap(int[] a, int i, int j) {int temp = a[i];a[i] = a[j];a[j] = temp;}
}

http://www.lryc.cn/news/477374.html

相关文章:

  • 20241105,LeetCode 每日一题,用 Go 实现两数之和的非暴力解法
  • mysql之命令行基础指令
  • 使用Django Channels实现WebSocket实时通信
  • 「Mac畅玩鸿蒙与硬件27」UI互动应用篇4 - 猫与灯的互动应用
  • Spring-Day4
  • C#-类:成员属性
  • qt QDragEnterEvent详解
  • Vue项目与IE浏览器的兼容性分析(Vue|ElementUI)
  • 【C++之STL】一文学会使用 string
  • 好用的办公套件--- ONLYOFFICE
  • Android View事件分发
  • 攻防世界GFSJ1229 Three
  • 2023 icpc杭州(M,J,D,G,H)
  • 在CentOS 7上安装Alist
  • 【C/C++】memcpy函数的模拟实现
  • 嵌入式开发之线程互斥
  • JavaScript 变量作用域与函数调用机制:var 示例详解
  • Linux(CentOS)安装 JDK
  • AI产品经理实战手册:策略、开发与商业化指南
  • 【大语言模型】ACL2024论文-06 探索思维链COT在多模态隐喻检测中的应用
  • Linux之初体验
  • 现代化水电管理:Spring Boot在大学城的实践
  • 黑马官网2024最新前端就业课V8.5笔记---HTML篇
  • GS-Blur数据集:首个基于3D场景合成的156,209对多样化真实感模糊图像数据集。
  • Linux下Java的多种方式安装
  • Android Studio:connect time out
  • A014-基于Spring Boot的家电销售展示平台设计与实现
  • 数学期望和联合概率密度
  • 萤石私有化设备视频平台EasyCVR视频融合平台如何构建农业综合监控监管系统?
  • 【MongoDB】Windows/Docker 下载安装,MongoDB Compass的基本使用、NoSQL、MongoDB的基础概念及基础用法(超详细)