LeetCode #155 - 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.

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.

实现一个最小栈,必须能够以O(1)的时间复杂度得到栈中的最小值。具体方法是利用两个栈,一个按压栈顺序存储数值,一个按照当前最小值存储数值。

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {}
    
    void push(int x) {
        s1.push(x);
        if(s2.empty()) s2.push(x);
        else s2.push(min(s2.top(),x));
    }
    
    void pop() {
        s1.pop();
        s2.pop();
    }
    
    int top() {
        return s1.top();
    }
    
    int getMin() {
        return s2.top();
    }
    
private:
    stack<int> s1;
    stack<int> s2;
};

猜你喜欢

转载自blog.csdn.net/LawFile/article/details/81182074