欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

155. Min Stack

程序员文章站 2024-01-19 17:21:22
...

155. Min Stack
155. Min Stack

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
    }

    void push(int x) {
        s1.push(x);
        if(s2.empty())
            s2.push(x);
        else
            s2.push(x<s2.top()?x:s2.top());
    }

    void pop() {
        s1.pop();
        s2.pop();
    }

    int top() {
        return s1.top();
    }

    int getMin() {
        return s2.top();
    }
private:
    stack<int> s1,s2;
};
class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
    sta=INT_MAX;
    }

    void push(int x) {
        if(x<=sta){
            s1.push(sta);
            sta=x;
        }
        s1.push(x);
    }

    void pop() {
        int t=s1.top();s1.pop();
        if(t==sta){
            sta=s1.top();
            s1.pop();
        }
    }

    int top() {
        return s1.top();
    }

    int getMin() {
        return sta;
    }
private:
    int sta;
    stack<int> s1;
};