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.

设计并实现一个stack,但是这个stack要随时都可以返回一个最小值。可以再申请一个stack存储当前stack中的最小值,同样的思路也可以解决Min Stack和Max Stack的问题。
C++ Code:

class MinStack {
private: 
         vector<int> mStack;
         vector<int> mMinStack;
         int mMinValue = 0;
public:
    void push(int x) {
        if (mStack.size() == 0)
            mMinValue = x;
        else
            mMinValue = mMinValue < x ? mMinValue : x;
        mStack.push_back(x);
        mMinStack.push_back(mMinValue);
    }

    void pop() {
        mStack.pop_back();
        mMinStack.pop_back();
        mMinValue = getMin();
    }

    int top() {
        if (mStack.size() > 0)
            return mStack[mStack.size() - 1];
        else
            return -1;
    }

    int getMin() {
        if (mMinStack.size() > 0)
            return mMinStack[mMinStack.size() - 1];
        else
            return -1;
    }
};

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