Java实现小根堆和大根堆(PriorityQueue)

编程入门 行业动态 更新时间:2024-10-27 08:25:39

Java实现<a href=https://www.elefans.com/category/jswz/34/1674918.html style=小根堆和大根堆(PriorityQueue)"/>

Java实现小根堆和大根堆(PriorityQueue)

Java里面的PriorityQueue底层默认使用的堆,所以我们使用PriorityQueue就能实现堆的功能。

1、小根堆实现

package test;import java.util.Comparator;
import java.util.PriorityQueue;/*add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常offer 添加一个元素并返回true 如果队列已满,则返回falsepoll 移除并返问队列头部的元素 如果队列为空,则返回nullpeek 返回队列头部的元素 如果队列为空,则返回null*/
public class Test {public static void main(String[] args) {PriorityQueue<Integer>priorityQueue = new PriorityQueue<>(new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {return o2pareTo(o1);}});for(int i = 10; i >= 0; i--){if(priorityQueue.size() < 5){priorityQueue.add(i);}else {priorityQueue.remove();priorityQueue.add(i);}}while (!priorityQueue.isEmpty()) {System.out.println(priorityQueue.remove());}}
}

2、大根堆

package test;import java.util.Comparator;
import java.util.PriorityQueue;/*add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常offer 添加一个元素并返回true 如果队列已满,则返回falsepoll 移除并返问队列头部的元素 如果队列为空,则返回nullpeek 返回队列头部的元素 如果队列为空,则返回null*/
public class Test {public static void main(String[] args) {PriorityQueue<Integer>priorityQueue = new PriorityQueue<>();for(int i = 0; i < 10; i++){if(priorityQueue.size() < 5){priorityQueue.add(i);}else {priorityQueue.remove();priorityQueue.add(i);}}while (!priorityQueue.isEmpty()) {System.out.println(priorityQueue.remove());}}
}

 

更多推荐

Java实现小根堆和大根堆(PriorityQueue)

本文发布于:2024-02-08 20:53:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1674919.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:小根堆   Java   PriorityQueue   大根堆

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!