716. 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.

基本思路同 153. Min Stack,用两个stack

注意popMax()的时候要先把stack中的元素pop出来,直到找到max,然后弹出max并把之前弹出的元素重新入栈。stack与maxStack始终同步操作

time: popMax() - O(n), others - O(1), space: O(n)

class MaxStack {
    LinkedList<Integer> stack;
    LinkedList<Integer> maxStack;

    /** initialize your data structure here. */
    public MaxStack() {
        stack = new LinkedList<>();
        maxStack = new LinkedList<>();
    }
    
    public void push(int x) {
        if(maxStack.isEmpty()) {
            maxStack.offerFirst(x);
        } else {
            maxStack.offerFirst(Math.max(x, maxStack.peekFirst()));
        }
        stack.offerFirst(x);
    }
    
    public int pop() {
        maxStack.pollFirst();
        return stack.pollFirst();
    }
    
    public int top() {
        return stack.peekFirst();
    }
    
    public int peekMax() {
        return maxStack.peekFirst();
    }
    
    public int popMax() {
        int max = maxStack.peekFirst();
        LinkedList<Integer> tmp = new LinkedList<>();
        while(stack.peekFirst() != max) {
            tmp.offerFirst(stack.pollFirst());
            maxStack.pollFirst();
        }
        stack.pollFirst();
        maxStack.pollFirst();
        while(!tmp.isEmpty()) {
            push(tmp.pollFirst());
        }
        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();
 */
原文地址:https://www.cnblogs.com/fatttcat/p/10229123.html