[LeetCode] 155. Min Stack

来源:互联网 发布:ss翻墙教程linux 编辑:程序博客网 时间:2024/05/16 01:45

思路:
用两个栈. 第一个栈存所有数据, 第二个栈实时更新第一个栈的最小值. 这样即使s1弹出了他当前的最小值, 我们还能在s2中查看到原第二小, 现在更新后的最小值.

class MinStack {public:    MinStack() {    }    void push(int x) {        s1.push(x);        if (s2.empty() || x <= getMin())            s2.push(x);    }    void pop() {        if (s1.top() == getMin())            s2.pop();        s1.pop();    }    int top() {        return s1.top();    }    int getMin() {        return s2.top();    }private:    stack<int> s1;    stack<int> s2;};
0 0
原创粉丝点击