LeetCode "Min Stack"

Not very hard to figure out an initial solution, with min heapmonoqstack. 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;
};
原文地址:https://www.cnblogs.com/tonix/p/4086883.html