码迷,mamicode.com
首页 > 其他好文 > 详细

Min Stack

时间:2016-05-23 00:29:25      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

这里面有一个注意的点是,如果现在要push x,且x等于当前存在的最小值(栈中已经有了x)时,也要把x进栈。否则当x出栈时,当前最小值也跟着出栈,但是原栈中最小值元素依然还有,此时最小值却发生了错误。
class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        s1.push(x);
        if(!s2.size())
            s2.push(x);
        else if(x<=s2.top())
            s2.push(x);
    }
    
    void pop() {
        if(s1.size())
        {
            if(s1.top()==s2.top())
            {
                s1.pop();
                s2.pop();
            }
            else
                s1.pop();
        }
    }
    
    int top() {
        return s1.top();
    }
    
    int getMin() {return s2.top();
    }

private:
    stack<int> s1;
    stack<int> s2;
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

Min Stack

标签:

原文地址:http://www.cnblogs.com/summerkiki/p/5518229.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!