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 2014-11-10 12:24  Tonix  阅读(154)  评论(0编辑  收藏  举报