zoukankan      html  css  js  c++  java
  • 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;
    };
  • 相关阅读:
    第二十一天作业
    第二十天:继承
    第二十天作业
    第十六天
    第十九天作业
    day53
    day52
    day51
    day50
    day44
  • 原文地址:https://www.cnblogs.com/tonix/p/4086883.html
Copyright © 2011-2022 走看看