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.

利用另外一個棧存儲棧中的最小值

class MinStack {
public:
    stack<int> myStack;
    stack<int> minStack;
    void push(int x) {
        myStack.push(x);
        if(minStack.empty() || minStack.top()>=x)
            minStack.push(x);
    }

    void pop() {
        if(myStack.top() == minStack.top())
            minStack.pop();
        
        myStack.pop();
    }

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

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章