[LeetCode] 155. Min Stack

题目链接:传送门

Description

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.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.

Solution

题意:

按题意实现 MinStack 的方法

思路:

模糊记得可以用差值的方法做,参考了 Discuss 的思路,注意边界处理

#define INF 2147483647;
#define LL long long
class MinStack {
private:
    stack<LL> s;
    LL Min;
public:
    /** initialize your data structure here. */
    MinStack() {
        Min = INF;
    }
    
    void push(int x) {
        if (s.empty()) {
            s.push(0LL);
            Min = x;
        } else {
            s.push(x - Min);
            if (x < Min)  Min = x;
        }
    }
    
    void pop() {
        if (s.empty())  return ;
        LL Top = s.top();
        s.pop();
        if (Top < 0) {
            Min = Min - Top;
        }
    }
    
    int top() {
        if (s.empty())  return INF;
        LL Top = s.top();
        if (Top > 0) {
            return Min + Top;
        } else {
            return Min;
        }
    }
    
    int getMin() {
        if (s.empty())  return INF;
        return Min;
    }
};

/**
 * 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();
 */
posted @ 2018-03-08 01:19  酒晓语令  阅读(74)  评论(0编辑  收藏  举报