Min Stack leetcode

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;
};

 

posted @ 2016-01-03 21:32  sdlwlxf  阅读(164)  评论(0编辑  收藏  举报