716. Max Stack

Hard
讲真这道题说不上Hard吧,对Stack, PriorityQueue稍微熟悉一点就能做,注意几点:

  • PriorityQueue的constructor,我一开始纠结于那个initial capacity要怎么填,那个comparator需不需要重写,然而还是太不熟悉。initial capacity写一个比较大的数字就可以了,integer默认是从小到大排列的,从大到小排列的话写一个Collections.reverseOrder()就可以了。

  • 关于popMax()方法,一开始我是没想到怎么做的。心想一个Stack要怎么pop出来里面最大的元素呢?原来是新建一个temp stack, 我们把原stack的peek元素一一pop出来放到temp里面,直到遇到真正需要取的那个max把它pop出去,再把原来暂存到temp stack里的元素重新push回到original stack, 很巧妙的方法.

class MaxStack {

    Stack<Integer> stack;
    PriorityQueue<Integer> pq;
    /** initialize your data structure here. */
    public MaxStack() {
        stack = new Stack<>();
        pq = new PriorityQueue<>(10000, Collections.reverseOrder());
    }
    
    public void push(int x) {
        stack.push(x);
        pq.offer(x);        
    }
    
    public int pop() {
        int top = stack.pop();
        pq.remove(top);
        return top;
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int peekMax() {
        return pq.peek();
    }
    
    public int popMax() {
        int max = pq.poll();
        Stack<Integer> temp = new Stack<>();
        while (stack.peek() != max){
            temp.push(stack.pop());
        }
        stack.pop();
        while (!temp.isEmpty()){
            stack.push(temp.pop());
        }
        return max; 
    }
}

/**
 * Your MaxStack object will be instantiated and called as such:
 * MaxStack obj = new MaxStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.peekMax();
 * int param_5 = obj.popMax();
 */
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/7118b50696eb
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞