LeetCode系列155—最小栈

题意

最小栈

题解

方法一:辅助栈

class MinStack {
    
    
    stack<int> st;
    stack<int> minStack;
public:
    /** initialize your data structure here. */
    MinStack() {
    
    }
    
    void push(int val) {
    
    
        st.push(val);
        if (minStack.empty() || val <= minStack.top())
            minStack.push(val);
    }
    
    void pop() {
    
    
        if (st.top() == minStack.top())
            minStack.pop();
        st.pop();
    }
    
    int top() {
    
    
        return st.top();
    }
    
    int getMin() {
    
    
        return minStack.top();
    }
};

おすすめ

転載: blog.csdn.net/younothings/article/details/120213315