[LeetCode] Min Stack 最小栈

 

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.

 

这道最小栈跟原来的栈相比就是多了一个功能,可以返回该栈的最小值。使用两个栈来实现,一个栈来按顺序存储push进来的数据,另一个用来存出现过的最小值。代码如下:

 

class MinStack {
public:
    void push(int x) {
        _stack.push(x);
        if (_minStack.empty() || x <= _minStack.top()) _minStack.push(x);
    }
    
    void pop() {
        if (!_stack.empty()) {
            if (_stack.top() == _minStack.top()) _minStack.pop();
            _stack.pop();
        }
    }
    
    int top() {
        if (!_stack.empty()) return _stack.top();
        return 0;
    }
    
    int getMin() {
        if (!_minStack.empty()) return _minStack.top();
        return 0;
    }
    
private:
    stack<int> _stack;
    stack<int> _minStack;
};

 

LeetCode All in One 题目讲解汇总(持续更新中...)

你可能感兴趣的:(LeetCode)