力扣leetcode 155. 最小栈 java

力扣leetcode 155. 最小栈 java_第1张图片

class MinStack {
    private Stack<Integer> S;
    private Stack<Integer> minS;

    /** initialize your data structure here. */
    public MinStack() {
        S = new Stack<Integer>();
        minS = new Stack<Integer>();
    }
    
    public void push(int x) {
        S.push(x);
        if(minS.isEmpty() || minS.peek() >= x) minS.push(x);
    }
    
    public void pop() {
        int x = S.pop();
        if(minS.peek() == x) minS.pop();
    }
    
    public int top() {
        return S.peek();
    }
    
    public int getMin() {
        return minS.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

你可能感兴趣的:(每日一题leetcode)