【数据结构】优先级队列

优先级队列简介

优先级队列也属于队列,因此也提供以下接口:

public interface Queue<E> {

	int size();	// 元素的数量
	
	boolean isEmpty();	// 是否为空
	
	void enQueue(E element);	// 入队
	
	E deQueue();	// 出队
	
	E front();	// 获取队列的头元素
	
	void clear();	// 清空
}

在这里插入图片描述

普通队列与优先级队列对比:

  • 普通的队列是 FIFO 原则,也就是先进先出

  • 优先级队列则是按照优先级高低进行出队,
    比如将优先级最高的元素作为队头优先出队。

优先级队列应用场景:

  • 医院的夜间门诊
    队列元素是病人
    优先级是病情的严重情况、挂号时间

  • 操作系统的多任务调度
    队列元素是任务
    优先级是任务类型

优先队列的底层实现

利用二叉堆作为优先队列的底层实现

可以通过 ComparatorComparable 去自定义优先级高低
在这里插入图片描述

二叉堆实现优先级队列代码

利用二叉堆实现优先级队列。

/**
 * 二叉堆实现优先级队列
 * @author yusael
 */
public class PriorityQueue<E> {
	private BinaryHeap<E> heap;
	
	// 通过 comparator 自定义优先级高低
	public PriorityQueue(Comparator<E> comparator) {
		heap = new BinaryHeap<>(comparator);
	}
	
	public PriorityQueue() {
		this(null);
	}
	
	public int size() {
		return heap.size();
	}

	public boolean isEmpty() {
		return heap.isEmpty();
	}
	
	public void clear() {
		heap.clear();
	}

	public void enQueue(E element) {
		heap.add(element);
	}

	public E deQueue() {
		return heap.remove();
	}

	public E front() {
		return heap.get();
	}
}

练习

◼ 数组中的第K个最大元素:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/

◼ 根据字符出现频率排序:https://leetcode-cn.com/problems/sort-characters-by-frequency/

◼ 数据流中的第K大元素:https://leetcode-cn.com/problems/kth-largest-element-in-a-stream/

◼ 有序矩阵中第K小的元素:https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/

◼ 前K个高频元素:https://leetcode-cn.com/problems/top-k-frequent-elements/

◼ 前K个高频单词:https://leetcode-cn.com/problems/top-k-frequent-words/

◼ 查找和最小的K对数字:https://leetcode-cn.com/problems/find-k-pairs-with-smallest-sums/

◼ 合并K个排序链表:https://leetcode-cn.com/problems/merge-k-sorted-lists/

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值