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

Min Stack leetcode

时间:2016-01-03 22:25:25      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.

使用一个栈,和一个保存最小值的变量min

栈中保存的元素是 新加数和当前min的差,然后更新min,使min保持最小

利用差值使每个栈元素可以包含两个信息量

class MinStack {
public:
    void push(int x) {
        if (sta.empty())
        {
            sta.push(0);
            min = x;
        }
        else
        {
            sta.push(x - min);
            if (x < min)
                min = x;            
        }
    }

    void pop() {
        if (sta.empty())
            return;
        long top = sta.top();
        if (top < 0)
            min = min - top;
        sta.pop();
    }

    int top() {
        if (sta.empty())
            return 0;
        long top = sta.top();
        if (top < 0)
            return min;
        else
            return min + top;
    }

    int getMin() {
        return min;
    }
private:
    stack<long> sta;
    long min;
};

 

Min Stack leetcode

标签:

原文地址:http://www.cnblogs.com/sdlwlxf/p/5097244.html

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