- 1. 优先级队列
- 1.1 概念
- 2. 优先级队列的模拟实现
- 2.1 堆的概念
- 2.2 堆的存储方式
- 3. 堆的创建
- 3.1 堆的向下调整
- 3.2 建堆的时间复杂度
- 4. 堆的插入和删除
- 4.1 堆的插入
- 4.2 堆的删除
- 5. 用堆模拟优先级队列
- 6. 常用接口介绍
- 6.1 PriorityQueue的特性
- 6.2 PriorityQueue常用接口介绍
- 6.3 插入/删除/获取优先级最高的元素
- 6.3 JDK 1.8中,PriorityQueue的扩容方式:
- 7. 应用优先级队列解决top-k问题
- 8. 堆的应用
- 8.1. 堆排序
- 8.2 利用堆的特点解决Top-k问题
- 前面介绍过队列,队列是一种先进先出(FIFO)的数据结构,但有些情况下,操作的数据可能带有优先级,一般出队列时,可能需要优先级高的元素先出队列,该中场景下,使用队列显然不合适,比如:在手机上玩游戏的时候,如果有来电,那么系统应该优先处理打进来的电话。
- 在这种情况下,我们的数据结构应该提供两个最基本的操作,一个是返回最高优先级对象,一个是添加新的对象。这种数据结构就是优先级队列(Priority Queue)。
JDK1.8中的PriorityQueue底层使用了堆的数据结构,而堆实际就是在完全二叉树的基础之上进行了一些元素的调整。
2.1 堆的概念如果有一个关键码的集合K = {k0,k1, k2,…,kn-1},把它的所有元素按完全二叉树的顺序存储方式存储 在一个一维数组中,并满足:Ki <= K2i+1 且 Ki<= K2i+2 (Ki >= K2i+1 且 Ki >= K2i+2) i = 0,1,2…,则称为 小堆(或大堆)。将根节点最大的堆叫做最大堆或大根堆,根节点最小的堆叫做最小堆或小根堆。
堆的性质:
- 堆中某个节点的值总是不大于或不小于其父节点的值;
- 堆总是一棵完全二叉树。
从堆的概念可知,堆是一棵完全二叉树,因此可以层序的规则采用顺序的方式来高效存储,
注意:对于非完全二叉树,则不适合使用顺序方式进行存储,因为为了能够还原二叉树,空间中必须要存储空节点,就会导致空间利用率比较低。
将元素存储到数组中后,可以根据二叉树章节的性质5对树进行还原。假设i为节点在数组中的下标,则有:
- 如果i为0,则i表示的节点为根节点,否则i节点的双亲节点为 (i - 1)/2
- 如果2 * i + 1 小于节点个数,则节点i的左孩子下标为2 * i + 1,否则没有左孩子
- 如果2 * i + 2 小于节点个数,则节点i的右孩子下标为2 * i + 2,否则没有右孩子
对于集合{ 27,15,19,18,28,34,65,49,25,37 }中的数据,如果将其创建成堆呢?
仔细观察上图后发现:根节点的左右子树已经完全满足堆的性质,因此只需将根节点向下调整好即可。
向下过程(以小堆为例):
- 让parent标记需要调整的节点,child标记parent的左孩子(注意:parent如果有孩子一定先是有左孩子)
- 如果parent的左孩子存在,即:child < size, 进行以下操作,直到parent的左孩子不存在
- parent右孩子是否存在,存在找到左右孩子中最小的孩子,让child进行标
- 将parent与较小的孩子child比较,如果:
(1)parent小于较小的孩子child,调整结束
(2)否则:交换parent与较小的孩子child,交换完成之后,parent中大的元素向下移动,可能导致子树不满足对的性质,因此需要继续向下调整,即parent = child;child = parent*2+1; 然后继续2。
private void shiftDown(int root,int len){//向下调整的时间复杂度为 O(log n);
int parent=root;
int child=2*parent+1;//至少有一个左孩子
while(child
if(child+1//有左孩子,child+1elem[parent]){
int tmp=elem[child];
elem[child]=elem[parent];
elem[parent]=tmp;
parent=child;
child=parent*2+1;
}else{
break;//此时说明已经是大根堆
}
}
}
3.2 建堆的时间复杂度
因为堆是完全二叉树,而满二叉树也是完全二叉树,此处为了简化使用满二叉树来证明(时间复杂度本来看的就是近似值,多几个节点不影响最终结果):
因此:建堆的时间复杂度为O(N)。
堆的插入总共需要两个步骤:
- 将元素插入队尾
- 向上调整
private void shiftUp(int child){//向上调整
int parent=(child-1)/2;
while(parent>0){
if(elem[child]>elem[parent]){
int tmp=elem[child];
elem[child]=elem[parent];
elem[parent]=tmp;
child=parent;
parent=(child-1)/2;
}else{
break;
}
}
}
public boolean isFull(){
return usedSize==elem.length;
}
public void push(int val){//插入数据————插到队尾,然后向上调整
if(isFull()){
elem= Arrays.copyOf(elem,2*elem.length);
}
elem[usedSize]=val;
shiftUp(usedSize);
usedSize++;
}
4.2 堆的删除
注意:堆的删除一定删除的是堆顶元素。具体如下:
- 将堆顶元素对堆中最后一个元素交换
- 将堆中有效数据个数减少一个
- 对堆顶元素进行向下调整
private void shiftDown(int root,int len){//向下调整的时间复杂度为 O(log n);
int parent=root;
int child=2*parent+1;//至少有一个左孩子
while(child
if(child+1//有左孩子,child+1elem[parent]){
int tmp=elem[child];
elem[child]=elem[parent];
elem[parent]=tmp;
parent=child;
child=parent*2+1;
}else{
break;//此时说明已经是大根堆
}
}
}
public void pop(){//将队尾元素放置队头,usedSize--,然后向下调整
if(empty()){
System.out.println("优先级队列为空");
return;
}
elem[0]=elem[usedSize-1];
usedSize--;
shiftDown(0,usedSize-1);
}
5. 用堆模拟优先级队列
public class TestHeap {
public int elem[];
public int usedSize;
public TestHeap(){
this.elem=new int[10];
}
private void shiftDown(int root,int len){//向下调整的时间复杂度为 O(log n);
int parent=root;
int child=2*parent+1;//至少有一个左孩子
while(child
if(child+1//有左孩子,child+1elem[parent]){
int tmp=elem[child];
elem[child]=elem[parent];
elem[parent]=tmp;
parent=child;
child=parent*2+1;
}else{
break;//此时说明已经是大根堆
}
}
}
public void createHeap(int []arr){//创建堆
for(int i=0;i
elem[i]=arr[i];
usedSize++;
}
for(int p=(usedSize-1-1)/2;p>=0;p--){
shiftDown(p,usedSize);
}
}
private void shiftUp(int child){//向上调整
int parent=(child-1)/2;
while(parent>0){
if(elem[child]>elem[parent]){
int tmp=elem[child];
elem[child]=elem[parent];
elem[parent]=tmp;
child=parent;
parent=(child-1)/2;
}else{
break;
}
}
}
public boolean isFull(){
return usedSize==elem.length;
}
public void push(int val){//插入数据————插到队尾,然后向上调整
if(isFull()){
elem= Arrays.copyOf(elem,2*elem.length);
}
elem[usedSize]=val;
shiftUp(usedSize);
usedSize++;
}
public boolean empty(){
return usedSize==0;
}
public void pop(){//将队尾元素放置队头,usedSize--,然后向下调整
if(empty()){
System.out.println("优先级队列为空");
return;
}
elem[0]=elem[usedSize-1];
usedSize--;
shiftDown(0,usedSize-1);
}
public int peek(){//获取队头元素
if(empty()){
System.out.println("优先级队列为空");
return -1;
}
return elem[0];
}
}
6. 常用接口介绍
6.1 PriorityQueue的特性
Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,本文主要介绍PriorityQueue。
关于PriorityQueue的使用要注意:
- 使用时必须导入PriorityQueue所在的包,即:import java.util.PriorityQueue;
- PriorityQueue中放置的元素必须要能够比较大小,不能插入无法比较大小的对象,否则会抛出ClassCastException异常
- 不能插入null对象,否则会抛出NullPointerException
- 没有容量限制,可以插入任意多个元素,其内部可以自动扩容
- 插入和删除元素的时间复杂度为O( log n );
- PriorityQueue底层使用了堆数据结构, (注意:此处大家可以不用管什么是堆,后文中有介绍)
- PriorityQueue默认情况下是小堆—即每次获取到的元素都是最小的元素
- 优先级队列的构造
此处只是列出了PriorityQueue中常见的几种构造方式,其他的学生们可以参考帮助文档。
示例:
//PriorityQueue中放置的元素必须能比较大小,所以将Student类型元素放入PriorityQueue中时,就可以使它拥有Comparable接口 class Student implements Comparable6.3 插入/删除/获取优先级最高的元素{ public int age; public Student(int age) { this.age = age; } @Override public int compareTo(Student o) { return o.age-this.age; } @Override public String toString() { return "Student{" + "age=" + age + '}'; } } public class testDemo { public static void main(String[] args) { PriorityQueue priorityQueue = new PriorityQueue<>();//PriorityQueue中放置的元素必须能比较大小 priorityQueue.offer(new Student(12)); priorityQueue.offer(new Student(3)); priorityQueue.offer(new Student(78)); System.out.println(priorityQueue.peek());//输出为3,说明是小根堆 } public static void main1(String[] args) { PriorityQueue priorityQueue = new PriorityQueue<>();//PriorityQueue中放置的元素必须能比较大小 priorityQueue.offer(12); priorityQueue.offer(3); priorityQueue.offer(78); int tmp = priorityQueue.peek(); System.out.println(tmp);//输出为3,说明是小根堆 } public static void main2(String[] args) { //将默认的小根堆变为大根堆 PriorityQueue priorityQueue = new PriorityQueue<>( new Comparator () { @Override public int compare(Integer o1, Integer o2) { return o2-o1; } } ); priorityQueue.offer(12); priorityQueue.offer(3); priorityQueue.offer(78); int tmp = priorityQueue.peek(); System.out.println(tmp);//输出为3,说明默认是小根堆 } }
- boolean offer(E e),插入元素e,插入成功返回true,如果e对象为空,抛出NullPointerException异常,注意:空间不够时候会进行扩容
- E peek() ,获取优先级最高的元素,如果优先级队列为空,返回null
- E poll() ,移除优先级最高的元素并返回,如果优先级队列为空,返回null
- int size(), 获取有效元素的个数
- void clear(),清空
- boolean isEmpty(),检测优先级队列是否为空,空返回true
代码:
public static void main(String[] args) {
int[] arr = {4,1,9,2,8,0,7,3,6,5};
PriorityQueue p = new PriorityQueue<>();//创建一个小堆
for (int e:arr) {
p.offer(e);//插入元素
}
System.out.println(p);
p.poll();//删除元素
System.out.println(p);
int x = p.peek();//获取堆顶元素,即最最小值
System.out.println(x);
int size = p.size();
System.out.println(size);
p.clear();
int size1 = p.size();
System.out.println(size1);
}
6.3 JDK 1.8中,PriorityQueue的扩容方式:
private void grow(int minCapacity) {
int oldCapacity = queue.length;
// Double size if small; else grow by 50%
int newCapacity = oldCapacity + ((oldCapacity < 64) ?
(oldCapacity + 2) :
(oldCapacity >> 1));
// overflow-conscious code
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
queue = Arrays.copyOf(queue, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
7. 应用优先级队列解决top-k问题
top-k问题:最大或者最小的前k个数据。比如:世界前500强公司
链接: LeetCode 面试题17.14.最小k个数
思路(以求最小k个数为例):
- 建立小堆
- 依次拿取k个堆顶元素
public int[] smallestK(int[] arr, int k) {
PriorityQueue q = new PriorityQueue<>();
for(int x:arr){
q.offer(x);
}
int []ret=new int[k];
for(int i=0;i
ret[i]=q.poll();
}
return ret;
}
8. 堆的应用
8.1. 堆排序
思路:
- 建堆
升序:建大堆
降序:建小堆 - 利用堆删除思想来排序
代码:以降序排列为例
class Heap{
int [] elem;
int usedSize;
public Heap(int [] arr){
elem = new int[arr.length];
for(int i=0;i
elem[i]=arr[i];
usedSize++;
}
}
@Override
public String toString() {
return "Heap{" +
"elem=" + Arrays.toString(elem) +
", usedSize=" + usedSize +
'}';
}
public void shiftDown(int parent,int len){
int child = parent*2+1;//左孩子
while(child
//判断有没有右孩子,有的话,将其与左孩子比较选出最大的
if(child+1elem[child+1]){
child=child+1;
}
if(elem[child]
int tmp = elem[child];
elem[child]=elem[parent];
elem[parent]=tmp;
parent=child;
child = parent*2+1;
}else {
break;
}
}
}
public void creatHeap(){//建立小堆
if(elem==null){
return;
}
for(int i=(usedSize-1-1)/2;i>=0;i--){
shiftDown(i,usedSize);
}
}
public void heapSort(){//降序排列
if(elem==null){
return;
}
creatHeap();//建立小堆
for(int i=usedSize-1;i>=0;i--){
int tmp = elem[0];
elem[0]=elem[i];
elem[i]=tmp;
shiftDown(0,i);
}
}
}
public class Test {
public static void main(String[] args) {
int []arr = {4,1,9,2,8,0,7,3,6,5};
Heap heap = new Heap(arr);
heap.heapSort();
System.out.println(heap);
}
}
8.2 利用堆的特点解决Top-k问题
思路:
- 前K大:建立K个元素的小堆,然后将后面的N-K个元素一一与堆顶元素对比,如果大于堆顶元素,就与堆顶元素交换,然后向下调整。
- 前K小:建立K个元素的大堆,然后将后面的N-K个元素一一与堆顶元素对比,如果小于堆顶元素,就与堆顶元素交换,然后向下调整。
public class Test {
public static void shiftDown(int parent,int []heap) {//向下调整
int child = parent * 2 + 1;//左孩子
while (child < heap.length) {
//判断有没有右孩子,有的话,将其与左孩子比较选出最大的
if (child + 1 < heap.length && heap[child] > heap[child + 1]) {
child = child + 1;
}
if (heap[child] < heap[parent]) {
int tmp = heap[child];
heap[child] = heap[parent];
heap[parent] = tmp;
parent = child;
child = parent * 2 + 1;
} else {
break;
}
}
}
public static void creatHeap(int []heap){//建立小堆
for(int i=(heap.length-1-1)/2;i>=0;i--){
//System.out.println(Arrays.toString(heap));
shiftDown(i,heap);
}
}
public static int[] top_k(int [] arr,int k){//前K大
if(k==0){
return null;
}
int []heap = new int[k];
for(int i=0;i
heap[i]=arr[i];
}
creatHeap(heap);//建立k个元素小堆
for(int i=k;i
int top = heap[0];
if(arr[i]>top){
heap[0]=arr[i];
shiftDown(0,heap);
}
}
return heap;
}
public static void main(String[] args) {
int []arr = {4,1,9,2,8,0,7,3,6,5};
int [] ret=top_k(arr,7);
System.out.println(Arrays.toString(ret));
}
}



