155. Min Stack

来源:互联网 发布:seo入门博客 编辑:程序博客网 时间:2024/05/23 13:32

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.

st1保存正常数据,st2作为辅助栈保存递减子序列

class MinStack {public:    void push(int x) {        st1.push(x);        if(st2.empty())        {            st2.push(x);        }else        {            if(st2.top() >= x)            {                st2.push(x);            }        }    }    void pop() {        if(st1.top() <= st2.top())        {            st2.pop();        }        st1.pop();    }    int top() {        return st1.top();    }    int getMin() {        return st2.top();    }private:    stack<int> st1;    stack<int> st2;};
0 0