优先级队列
1.概念:队列是一种先进先出(FIFO)的数据结构,但有些情况下,操作的数据可能带有优先级,一般出队列时,可能需要优先级高的元素先出队列,该中场景下,使用队列显然不合适,在这种情况下,我们的数据结构应该提供两个最基本的操作,一个是返回最高优先级对象,一个是添加新的对象,这种数据结构就是优先级队列(Priority Queue)。
Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的。
2.PriorityQueue的特性:
(1)使用时必须导入PriorityQueue所在的包,即:
import java.util.PriorityQueue;
(2)PriorityQueue中放置的元素必须要能够比较大小,不能插入无法比较大小的对象,否则会抛出ClassCastException异常
(3) 不能插入null对象,否则会抛出NullPointerException
(4)没有容量限制,可以插入任意多个元素,其内部可以自动扩容
(5)插入和删除元素的时间复杂度为O(log2N) 【log以2为底的N】
(6)PriorityQueue底层使用了堆数据结构
3.PriorityQueue的常用构造方法:
构造器 | 功能介绍 |
PriorityQueue() | 创建一个空的优先级队列,默认容量是11 |
PriorityQueue(int initialCapacity) | 创建一个初始容量为initialCapacity的优先级队列,注意:initialCapacity不能小于1,否则会抛IllegalArgumentException异常 |
PriorityQueue(Collection<? extends E>c) | 用一个集合来创建优先级队列 |
代码实现:
import java.util.PriorityQueue;
public class TestPriorityQueue {
public static void TestPriorityQueue() {
//1.构造一个空的优先级队列 注意:空的优先级队列,但是底层已经有了11个默认空间;
PriorityQueue<Integer> p1 = new PriorityQueue<>();
//2.按照指定容量来进行构造
PriorityQueue<Integer> p2 = new PriorityQueue<>(20);
//3.可以用一个集合来直接构造优先级队列,将来就会将集合中的元素放到优先级队列中
List<Integer> L = new ArrayList<>();
L.add(4);
L.add(0);
L.add(3);
L.add(2);
L.add(1);
System.out.println(L);
PriorityQueue<Integer> p3 = new PriorityQueue<>(L);
System.out.println(p3.size());
}
}
4.PriorityQueue的常用方法:
函数名 | 功能介绍 |
boolean offer(E e) | 插入元素e,插入成功返回true,如果e对象为空,抛出NullPointerException异常,时间复杂度,注意:空间不够时候会进行扩容 |
E peek() | 获取优先级最高的元素,如果优先级队列为空,返回null |
E poll() | 移除优先级最高的元素并返回,如果优先级队列为空,返回null |
int size() | 获取有效元素的个数 |
void clear() | 清空 |
boolean isEmpty() | 检测优先级队列是否为空,空返回true |
代码实现:
import java.util.PriorityQueue;
public class TestPriorityQueue {
public static void TestPriorityQueue(){
PriorityQueue<Integer> p =new PriorityQueue<>();
p.offer(4);
p.offer(1);
p.offer(3);
p.offer(0);
p.offer(5);
p.offer(2);
System.out.println(p);
//peek();取优先级队列中第一个(最小的)元素
//poll();删除优先级队列中第一个元素(最小的)元素
// 剩余元素会自动进行调整---->将剩余元素中最小的元素调整到首元素位置
System.out.println(p.peek());
p.poll();
System.out.println(p.peek());
p.poll();
System.out.println(p.peek());
System.out.println(p.size());
p.clear();
if (p.isEmpty()){
System.out.println("优先级队列已经为空");
}
else{
System.out.println("优先级队列不为空");
}
}
public static void main(String[] args) {
TestPriorityQueue();
}
}
//打印结果:
/*
[0, 1, 2, 4, 5, 3]
0
1
2
4
优先级队列已经为空
*/
5.top-k问题:
力扣:最小的K个数 设计一个算法,找出数组中最小的k个数。以任意顺序返回这k个数均可。
class Solution {
public int[] smallestK(int[] arr, int k) {
if(arr == null || k <= 0){
return new int[0];
}
PriorityQueue<Integer> p = new PriorityQueue<>(arr.length);
for(int i = 0; i < arr.length; ++i){
p.offer(arr[i]);
}
int[] ret = new int[k];
for(int i = 0;i < k; ++i){
ret[i] = p.peek();
p.poll();
}
return ret;
}
}
优先级队列的模拟实现
堆
1.概念:
如果有一个关键码的集合K = {k0,k1, k2,…,kn-1},把它的所有元素按完全二叉树的顺序存储方式存储 在一个一维数组中,并满足:Ki <= K2i+1 且 Ki<= K2i+2 (Ki >= K2i+1 且 Ki >= K2i+2) i = 0,1,2…,则称为 小堆(或大堆)。将根节点最大的堆叫做最大堆或大根堆,根节点最小的堆叫做最小堆或小根堆。
2.性质:
(1)堆中某个节点的值总是不大于或不小于其父节点的值;
(2)堆总是一棵完全二叉树。
3.堆的储存:
堆是一棵完全二叉树,因此可以层序的规则采用顺序的方式来高效存储,注意:对于非完全二叉树,则不适合使用顺序方式进行存储,因为为了能够还原二叉树,空间中必须要存储空节点,就会导致空间利用率比较低。
4.小堆的性质:
(1)堆顶元素一定是最小的
(2)每个节点都比其孩子小
(3)每条路径都是升序
(4)堆是一棵完全二叉树,一般将其存储在数组中
5.堆的创建及向下调整:
(小堆)
(1) 让parent标记需要调整的节点,child标记parent的左孩子(注意:parent如果有孩子一定先是有左孩子)
(2) 如果parent的左孩子存在,即:child < size, 进行以下操作,直到parent的左孩子不存在
<1> parent右孩子是否存在,存在找到左右孩子中最小的孩子,让child进行标
<2> 将parent与较小的孩子child比较,如果:parent小于较小的孩子child,调整结束
否则:交换parent与较小的孩子child,交换完成之后,parent中大的元素向下移动,可能导致子树不满足对的性质,因此需要继续向下调整,即parent = child;child = parent*2+1; 然后继续 (2) 。
代码实现:2
public class MyPriorityQueue {
private int[] array;
public MyPriorityQueue(){
array = new int[11];
size = 0;
}
public MyPriorityQueue(int[] arr){
array = new int[arr.length];
for (int i = 0;i < arr.length; ++i ){
array[i] = arr[i];
}
//将array中的元素调整,满足小堆的性质
//找倒数第一个非叶子节点
int lastLeaf = (array.length-2)>>1;
for (int root = lastLeaf; root>=0;root--){
shifDown(root);
}
}
//parent表示本次需要调整的节点的下标,调整以parent为根的二叉树
//注意:调整之前,一定要保证parent的左右子数已经满足小堆的性质
// 如果要检测parent是否满足小堆的性质,只需要使用parent与其孩子进行比较
//满足小堆性质----》说明以parent为根的二叉树已经是小堆
//不满足小堆的性质---》说明parent比其孩子大,此时需要将parent与其较小的孩子进行交换
//交换完以后,parent较大的元素向下移动,可能导致其子树不满足小堆的性质
//需要继续调整其子树
private void shifDown(int parent) {
//使用child标记parent的较小的孩子
//默认情况下先让其标记左孩子,因为parent可能有左孩子但是没有右孩子
int child = parent * 2 + 1;
while (child < size) {
//找parent中较小的孩子
//在用左右孩子比较时,必须保证右孩子存在--while循环条件已经保证了左孩子存在
if (child + 1 < size && array[child + 1] < array[child]) {
child += 1;
}
//检测较小的孩子是否比双亲小
if (array[child] < array[parent]) {
//说明parent不满足小堆的性质
swap(parent, child);
//parent较大的元素向下移动,可能导致其子树不满足小堆的性质
//继续向下调整
parent = child;
child = parent * 2 + 1;
} else {
//以parent为根的二叉树已经满足堆的性质
return;
}
}
}
private void swap(int parent, int child){
int temp = array[parent];
array[parent] = array[child];
array[child] = temp;
}
}
从根一路比较到叶子,比较的次数为完全二叉树的高度,即时间复杂度为
6.堆的插入:
(1) 先将元素放入到底层空间中(注意:空间不够时需要扩容)
(2) 将最后新插入的节点向上调整,直到满足堆的性质。
优先级队列的扩容说明:
(1) 如果容量小于64时,是按照oldCapacity2 + 2的方式扩容的
(2) 如果容量大于等于64,是按照oldCapacity2的方式扩容的
(3) 如果容量超过MAX_ARRAY_SIZE,按照MAX_ARRAY_SIZE来进行扩容
代码实现:
public class MyPriorityQueue {
private int[] array;
private int size = 0;
public MyPriorityQueue(){
array = new int[11];
size = 0;
}
boolean offer(int x){
//0.检测是否需要扩容
if (size>=array.length){
grow();
}
//1.先将元素尾插到数组中
array[size++] = x;
//2.检测新元素插入后是否破坏小堆的性质
shifUp(size-1);//注意:此处一定不能使用size--;
return true;
}
private void shifUp(int child){
int parent = (child-1)>>1;
while (child!=0){
if (array[child] < array[parent]){
swap(child,parent);
child = parent;
parent = (child-1)>>1;
}else {
return;
}
}
//扩容
//知识模拟标准库中优先级队列扩容的一部分
private void grow(){
int oldCapacity = array.length;
int newCapacity = oldCapacity +( (oldCapacity < 64)?(oldCapacity+2):(oldCapacity>>1));
array = Arrays.copyOf(array,newCapacity);
}
private void swap(int parent, int child){
int temp = array[parent];
array[parent] = array[child];
array[child] = temp;
}
}
7.堆的删除:
(1) 将堆顶元素对堆中最后一个元素交换
(2) 将堆中有效数据个数减少一个
(3) 对堆顶元素进行向下调整
代码实现:
//删除:删除堆顶的元素
int poll(){
int ret = array[0];
swap(0,size-1);
size--;
shifDown(0);
return 0;
}
用堆模拟实现优先级队列
代码实现:
public class MyPriorityQueue {
private int[] array;
private int size = 0;
public MyPriorityQueue(){
array = new int[11];
size = 0;
}
public MyPriorityQueue(int initCapacity){
if (initCapacity < 1) {
initCapacity = 11;
}
array = new int[initCapacity];
size = 0;
}
//标准库中没有该接口
public MyPriorityQueue(int[] arr){
array = new int[arr.length];
for (int i = 0;i < arr.length; ++i ){
array[i] = arr[i];
}
size = array.length;
//将array中的元素调整,满足小堆的性质
//找倒数第一个非叶子节点
int lastLeaf = (array.length-2)>>1;
for (int root = lastLeaf; root>=0;root--){
shifDown(root);
}
}
//获取堆顶元素
int peek(){
//标准库中,如果优先级队列是空,无法获取堆顶元素,因此返回的是空null
return array[0];
}
//向优先级队列中插入元素
boolean offer(int x){
//0.检测是否需要扩容
if (size>=array.length){
grow();
}
//1.先将元素尾插到数组中
array[size++] = x;
//2.检测新元素插入后是否破坏小堆的性质
shifUp(size-1);//注意:此处一定不能使用size--;
return true;
}
//删除:删除堆顶的元素
int poll(){
int ret = array[0];
swap(0,size-1);
size--;
shifDown(0);
return 0;
}
boolean isEmpty(){
return 0 == size;
}
int size(){
return size;
}
void clear(){
size = 0;
}
private void shifUp(int child){
int parent = (child-1)>>1;
while (child!=0){
if (array[child] < array[parent]){
swap(child,parent);
child = parent;
parent = (child-1)>>1;
}else {
return;
}
}
}
//扩容
//知识模拟标准库中优先级队列扩容的一部分
private void grow(){
int oldCapacity = array.length;
int newCapacity = oldCapacity +( (oldCapacity < 64)?(oldCapacity+2):(oldCapacity>>1));
array = Arrays.copyOf(array,newCapacity);
}
//parent表示本次需要调整的节点的下标,调整以parent为根的二叉树
//注意:调整之前,一定要保证parent的左右子数已经满足小堆的性质
// 如果要检测parent是否满足小堆的性质,只需要使用parent与其孩子进行比较
//满足小堆性质----》说明以parent为根的二叉树已经是小堆
//不满足小堆的性质---》说明parent比其孩子大,此时需要将parent与其较小的孩子进行交换
//交换完以后,parent较大的元素向下移动,可能导致其子树不满足小堆的性质
//需要继续调整其子树
private void shifDown(int parent) {
//使用child标记parent的较小的孩子
//默认情况下先让其标记左孩子,因为parent可能有左孩子但是没有右孩子
int child = parent * 2 + 1;
while (child < size) {
//找parent中较小的孩子
//在用左右孩子比较时,必须保证右孩子存在--while循环条件已经保证了左孩子存在
if (child + 1 < size && array[child + 1] < array[child]) {
child += 1;
}
//检测较小的孩子是否比双亲小
if (array[child] < array[parent]) {
//说明parent不满足小堆的性质
swap(parent, child);
//parent较大的元素向下移动,可能导致其子树不满足小堆的性质
//继续向下调整
parent = child;
child = parent * 2 + 1;
} else {
//以parent为根的二叉树已经满足堆的性质
return;
}
}
}
private void swap(int parent, int child){
int temp = array[parent];
array[parent] = array[child];
array[child] = temp;
}
public static void main(String[] args) {
int array[] = {5,3,7,1,4,6,8,0,2};
MyPriorityQueue mp = new MyPriorityQueue(array);
mp.offer(9);
System.out.println(mp.peek());
System.out.println(mp.size());
mp.offer(-1);
System.out.println(mp.peek());
System.out.println(mp.size());
mp.poll();
System.out.println(mp.peek());
System.out.println(mp.size());
mp.clear();
if (mp.isEmpty()){
System.out.println("空");
}else {
System.out.println("非空");
}
}
}
//打印结果
/*
10
-1
11
0
10
空
*/
运用比较器的优先级队列的实现
import java.util.Arrays;
/**
* @ClassName MyPriorityQueue
* @Description TODO MyPriorityQueue
* @Author 张洋
* @Date 2020/3/26 16:03
* @Version 2018.1.5
**/
interface Comp{
public int compare(int left,int right);
}
class Less implements Comp {
public int compare(int left,int right){
return left - right;
}
}
class Greater implements Comp{
public int compare(int left,int right){
return right - left;
}
}
public class MyPriorityQueue {
private int[] array;
private int size = 0;
Comp compare = null;
public MyPriorityQueue(Comp com){
array = new int[11];
compare = com;
}
public MyPriorityQueue(int initCapacity,Comp com){
if (initCapacity < 1) {
initCapacity = 11;
}
array = new int[initCapacity];
compare = com;
}
//标准库中没有该接口
public MyPriorityQueue(int[] arr,Comp com){
array = new int[arr.length];
for (int i = 0;i < arr.length; ++i ){
array[i] = arr[i];
}
size = array.length;
compare = com;
//将array中的元素调整,满足小堆的性质
//找倒数第一个非叶子节点
int lastLeaf = (array.length-2)>>1;
for (int root = lastLeaf; root>=0;root--){
shifDown(root);
}
}
//获取堆顶元素
int peek(){
//标准库中,如果优先级队列是空,无法获取堆顶元素,因此返回的是空null
return array[0];
}
//向优先级队列中插入元素
boolean offer(int x){
//0.检测是否需要扩容
if (size>=array.length){
grow();
}
//1.先将元素尾插到数组中
array[size++] = x;
//2.检测新元素插入后是否破坏小堆的性质
shifUp(size-1);//注意:此处一定不能使用size--;
return true;
}
//删除:删除堆顶的元素
int poll(){
int ret = array[0];
swap(0,size-1);
size--;
shifDown(0);
return 0;
}
boolean isEmpty(){
return 0 == size;
}
int size(){
return size;
}
void clear(){
size = 0;
}
private void shifUp(int child){
int parent = (child-1)>>1;
while (child!=0){
//if (array[child] < array[parent]){
if (compare.compare(array[child],array[parent]) < 0){
swap(child,parent);
child = parent;
parent = (child-1)>>1;
}else {
return;
}
}
}
//扩容
//知识模拟标准库中优先级队列扩容的一部分
private void grow(){
int oldCapacity = array.length;
int newCapacity = oldCapacity +( (oldCapacity < 64)?(oldCapacity+2):(oldCapacity>>1));
array = Arrays.copyOf(array,newCapacity);
}
//parent表示本次需要调整的节点的下标,调整以parent为根的二叉树
//注意:调整之前,一定要保证parent的左右子数已经满足小堆的性质
// 如果要检测parent是否满足小堆的性质,只需要使用parent与其孩子进行比较
//满足小堆性质----》说明以parent为根的二叉树已经是小堆
//不满足小堆的性质---》说明parent比其孩子大,此时需要将parent与其较小的孩子进行交换
//交换完以后,parent较大的元素向下移动,可能导致其子树不满足小堆的性质
//需要继续调整其子树
private void shifDown(int parent) {
//使用child标记parent的较小的孩子
//默认情况下先让其标记左孩子,因为parent可能有左孩子但是没有右孩子
int child = parent * 2 + 1;
while (child < size) {
//找parent中较小的孩子
//在用左右孩子比较时,必须保证右孩子存在--while循环条件已经保证了左孩子存在
//if (child + 1 < size && array[child + 1] < array[child]) {
if (child+1 < size && compare.compare(array[child+1],array[child]) < 0){
child += 1;
}
//检测较小的孩子是否比双亲小
//if (array[child] < array[parent]) {
if (compare.compare(array[child],array[parent]) < 0){
//说明parent不满足小堆的性质
swap(parent, child);
//parent较大的元素向下移动,可能导致其子树不满足小堆的性质
//继续向下调整
parent = child;
child = parent * 2 + 1;
} else {
//以parent为根的二叉树已经满足堆的性质
return;
}
}
}
private void swap(int parent, int child){
int temp = array[parent];
array[parent] = array[child];
array[child] = temp;
}
public static void main(String[] args) {
int array[] = {5,3,7,1,4,6,8,0,2};
MyPriorityQueue mp = new MyPriorityQueue(array,new Less()); //new Less()小堆,new Greater()大堆
mp.offer(9);
System.out.println(mp.peek());
System.out.println(mp.size());
mp.offer(-1);
System.out.println(mp.peek());
System.out.println(mp.size());
mp.poll();
System.out.println(mp.peek());
System.out.println(mp.size());
mp.clear();
if (mp.isEmpty()){
System.out.println("空");
}else {
System.out.println("非空");
}
}
}