美文网首页
13.Min Stack

13.Min Stack

作者: Anaven | 来源:发表于2017-01-02 17:42 被阅读0次

https://leetcode.com/problems/min-stack/

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> stk, minstk;
    
    MinStack() {
        
    }
    
    int top() {
        return stk.top();
    }

    void push(int x) {
        stk.push(x);
        if (minstk.empty() || x <= minstk.top()) {
            minstk.push(x);
        }
    }

    int pop() {
        int top = stk.top();
        stk.pop();
        if (top == minstk.top()) {
            minstk.pop();
        }
        return top;
    }

    int getMin() {
        return minstk.top();
    }
};

/**
 * 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();
 */

相关文章

网友评论

      本文标题:13.Min Stack

      本文链接:https://www.haomeiwen.com/subject/gvgwvttx.html