Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Not very hard to figure out an initial solution, with min heap\monoq\stack. But the key idea is to avoid unnecessary book-keeping when new value is larger than current min value.

复制代码
class MinStack 
{
public:

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

    void pop() {
        if (!stk.empty())
        {
            if (minstk.top() == stk.top())
            {
                minstk.pop();
            }
            stk.pop();
        }
    }

    int top() {
        if (!stk.empty())
        {
            return stk.top();
        }
        return -1;
    }

    int getMin() {
        if (!minstk.empty())
        {
            return minstk.top();
        }
        return -1;
    }

private:
    std::stack<int> stk;
    std::stack<int> minstk;
};
复制代码
posted on   Tonix  阅读(155)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示