堆(优先级队列 PriorityQueue)

堆(优先级队列 PriorityQueue)

通过题目讲解

题目链接博客合并果子(优先级队列)
在这里插入图片描述

提交代码

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)

遍历方式

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 */
	}

排序

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]*/
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

极客李华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值