堆(优先级队列 PriorityQueue)

╰+哭是因爲堅強的太久メ 2024-03-31 16:11 216阅读 0赞

堆(优先级队列 PriorityQueue)

通过题目讲解

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

提交代码

  1. import java.io.*;
  2. import java.util.*;
  3. public class Main
  4. {
  5. public static void main(String[] args) {
  6. Scanner in = new Scanner(System.in);
  7. PriorityQueue<Integer> q = new PriorityQueue<Integer>();
  8. int n = in.nextInt();
  9. for (int i = 0; i < n; ++ i)
  10. {
  11. q.add(in.nextInt());
  12. }
  13. int sum = 0;
  14. while(q.size()>1)
  15. {
  16. int a = q.poll();
  17. int b = q.poll();
  18. sum += a + b;
  19. q.add(a + b);
  20. }
  21. System.out.println(sum);
  22. }
  23. }

常用方法

和Queue一样
参考文档:队列(Queue)

遍历方式

  1. public static void main(String[] args) {
  2. PriorityQueue<Integer> pqueue = new PriorityQueue<Integer>();
  3. pqueue.add(100);
  4. pqueue.add(10);
  5. pqueue.add(11);
  6. pqueue.add(1);
  7. pqueue.add(646);
  8. System.out.println(pqueue);
  9. /*[1, 10, 11, 100, 646]*/
  10. for (Integer it : pqueue)
  11. {
  12. System.out.print(it + " ");
  13. }
  14. /*1 10 11 100 646 */
  15. System.out.println();
  16. Iterator<Integer> it = pqueue.iterator();
  17. while(it.hasNext())
  18. {
  19. System.out.print(it.next() + " ");
  20. }
  21. /*1 10 11 100 646 */
  22. }

排序

  1. public static void main(String[] args) {
  2. // 默认排序规则是升序排列
  3. // 可以自定义排序规则
  4. PriorityQueue<Integer> pqueue = new PriorityQueue<Integer>(new Comparator<Integer>() {
  5. @Override
  6. public int compare(Integer o1, Integer o2) {
  7. int num = 0;
  8. if (o1 > o2) num = -1;
  9. else num = 1;
  10. return num;
  11. }
  12. });
  13. pqueue.add(100);
  14. pqueue.add(10);
  15. pqueue.add(11);
  16. pqueue.add(1);
  17. pqueue.add(646);
  18. System.out.println(pqueue);
  19. /*[646, 100, 11, 1, 10]*/
  20. }

发表评论

表情:
评论列表 (有 0 条评论,216人围观)

还没有评论,来说两句吧...

相关阅读

    相关 PriorityQueue(优先级队列总结)

    一,概念 > 队列是一种先进先出(FIFO)的数据结构,但有些情况下,操作的数据可能带有优先级,一般出队列时,可能需要优先级高的元素先出队列 > 数据结构应该