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.
这题想到用另外一个stack存储最小值的话,特别简单,下面是代码:
class MinStack {
public:
    void push(int x) {
        if(s.empty())
            min.push(x);
        else
            min.push(x<min.top()?x:min.top());
        s.push(x);
    }

    void pop() {
        if(s.empty())
            return ;
        else
        {
            s.pop();
            min.pop();
        }
    }

    int top() {
        return s.top();
    }

    int getMin() {
        return min.top();
    }
    
private:
    std::stack<int> s;
    std::stack<int> min;
};


你可能感兴趣的:(Min Stack —— Leetcode)