underwindfall / Algorithme

练习总结算法的地方
https://qifanyang.com/resume
1 stars 0 forks source link

LCOF30 #343

Open underwindfall opened 2 years ago

underwindfall commented 2 years ago
 class MinStack {
        Stack<Integer> stack;

        Stack<Integer> minStack;

        MinStack() {
            stack = new Stack<>();
            minStack = new Stack<>();
        }

        // time O(1)
        // space O(n)
        public void push(int x) {
            stack.push(x);
            if (minStack.isEmpty() || x <= minStack.peek()) {
                minStack.push(x);
            }
        }

        // time O(1)
        // space O(n)
        public void pop() {
            Integer element = stack.pop();
            if (element.equals(minStack.peek())) {
                minStack.pop();
            }
        }

        // time O(1)
        // space O(n)
        public int top() {
            return stack.peek();
        }

        // time O(1)
        // space O(n)
        public int getMin() {
            return minStack.peek();
        }
    }