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.
思路:问题的关键在于pop操作可能会pop出stack的最小值,因此需要额外维护一个栈记录最小值的出现情况。 If a new element is larger than the current minimum, we do not need to push it on to the min stack. When we perform the pop operation, check if the popped element is the same as the current minimum. If it is, pop it off the min stack too.

#include 
using namespace std;

class MinStack {
private: 
    stack content;
    stack mins;
public:
    void push(int x) {
        content.push(x);
        //must add =, duplicate elements.
        if(mins.empty() || x <= mins.top())
            mins.push(x);
    }

    void pop() {
        int top = content.top();
        content.pop();
        if(top == mins.top())
        {
            mins.pop();
        }
    }

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

    int getMin() {
        return mins.top();
    }
};


你可能感兴趣的:(leetcode)