【剑指offer】【栈】30.包含min函数的栈

题目链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/

维护两个栈:栈st存储所有元素,minSt是一个单调栈,栈顶元素为min
1. 入栈:st.push(x); 若minSt.top >= x或minSt为空,x入栈minSt
2. 出栈:若minSt与st栈顶元素相同,则二者都出栈,否则st出栈
3. 获取最小值:若minSt不为空,返回minSt栈顶元素

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

/**
 * 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();
 */
posted @ 2020-03-29 12:05  NaughtyCoder  阅读(70)  评论(0)    收藏  举报