前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >堆(优先级队列 PriorityQueue)

堆(优先级队列 PriorityQueue)

作者头像
GeekLiHua
发布2025-01-21 15:48:17
发布2025-01-21 15:48:17
8000
代码可运行
举报
文章被收录于专栏:JavaJava
运行总次数:0
代码可运行

堆(优先级队列 PriorityQueue)

通过题目讲解

题目链接博客合并果子(优先级队列)

提交代码

代码语言:javascript
代码运行次数:0
复制
import java.io.*;
import java.util.*;

public class Main
{	
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		PriorityQueue<Integer> q = new PriorityQueue<Integer>();
		int n = in.nextInt();
		for (int i = 0; i < n; ++ i)
		{
			q.add(in.nextInt());
		}
		int sum = 0;
		while(q.size()>1)
		{
			int a = q.poll();
			int b = q.poll();
			sum += a + b;
			q.add(a + b);
		}
		System.out.println(sum);
	}
}

常用方法

和Queue一样

参考文档队列(Queue)

遍历方式

代码语言:javascript
代码运行次数:0
复制
public static void main(String[] args) {
		PriorityQueue<Integer> pqueue = new PriorityQueue<Integer>();			
		pqueue.add(100);
		pqueue.add(10);
		pqueue.add(11);
		pqueue.add(1);
		pqueue.add(646);
		System.out.println(pqueue);
		/*[1, 10, 11, 100, 646]*/
		
		for (Integer it : pqueue)
		{
			System.out.print(it + " ");
		}
		/*1 10 11 100 646 */
		System.out.println();
		Iterator<Integer> it = pqueue.iterator();
		while(it.hasNext())
		{
			System.out.print(it.next() + " ");
		}
		/*1 10 11 100 646 */
	}

排序

代码语言:javascript
代码运行次数:0
复制
public static void main(String[] args) {
		// 默认排序规则是升序排列
		// 可以自定义排序规则
		PriorityQueue<Integer> pqueue = new PriorityQueue<Integer>(new Comparator<Integer>() {

			@Override
			public int compare(Integer o1, Integer o2) {
				int num = 0;
				if (o1 > o2) num = -1;
				else num = 1;
				return num;
			}
			
		});			
		pqueue.add(100);
		pqueue.add(10);
		pqueue.add(11);
		pqueue.add(1);
		pqueue.add(646);
		System.out.println(pqueue);
		/*[646, 100, 11, 1, 10]*/
	}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-01-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 堆(优先级队列 PriorityQueue)
    • 通过题目讲解
    • 常用方法
    • 遍历方式
    • 排序
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档