Max Stack

Design a max stack that supports push, pop, top, peekMax and popMax.

  1. push(x) -- Push element x onto stack.
  2. pop() -- Remove the element on top of the stack and return it.
  3. top() -- Get the element on the top.
  4. peekMax() -- Retrieve the maximum element in the stack.
  5. popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.

Example 1:

MaxStack stack = new MaxStack();
stack.push(5); 
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5

Note:

  1. -1e7 <= x <= 1e7
  2. Number of operations won't exceed 10000.
  3. The last four operations won't be called when stack is empty.

思路:难点在于popmax,需要把当前max stack的peek 从stack里面remove掉,同时更新当前的max,用个temp stack解决,存储当前的Integer到max的值,然后再存储回来;

class MaxStack {
    private Stack<Integer> stack;
    private Stack<Integer> maxstack;

    public MaxStack() {
        this.stack = new Stack<>();
        this.maxstack = new Stack<>();
    }
    
    public void push(int x) {
        stack.push(x);
        if(maxstack.isEmpty() || maxstack.peek() <= x) {
            maxstack.push(x);
        }
    }
    
    public int pop() {
        int value = stack.pop();
        if(value == maxstack.peek()) {
            maxstack.pop();
        }
        return value;
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int peekMax() {
        return maxstack.peek();
    }
    
    public int popMax() {
        int maxvalue = maxstack.pop();
        Stack<Integer> temp = new Stack<>();
        while(stack.peek() != maxvalue) {
            temp.push(stack.pop());
        }
        stack.pop();
        while(!temp.isEmpty()) {
            // 注意这里是push,不是stack.push; 
            // 因为maxstack也要push;
            push(temp.pop());
        }
        return maxvalue;
    }
}

/**
 * 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();
 */

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值