题解 | 两端问优先队列

两端问优先队列

https://www.nowcoder.com/practice/da2887a3fd8549ad826c9cbdaa67f513

import java.util.*;
//一个小根堆,一个大根堆,注意在删除的时候要保证两个堆元素一致
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        // 小根堆(默认):最小元素在堆顶
        PriorityQueue<Integer> q1 = new PriorityQueue<>();

// 大根堆:最大元素在堆顶
        PriorityQueue<Integer> q2 = new PriorityQueue<>
        ((a,b)->b-a);
        int n=in.nextInt();
        while(n-->0){
            int op=in.nextInt();
            switch(op){
                case 1:
                int x=in.nextInt();
                q1.add(x);
                q2.add(x);
                break;
                case 2:
                System.out.println(q1.peek());
                break;
                case 3:
                System.out.println(q2.peek());
                break;
                case 4:
                 q2.remove(q1.peek());
                q1.poll();
               
                break;
                case 5:
                q1.remove(q2.peek());
                q2.poll();
                break;
            }
        }

    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务