1. 程式人生 > >leetcode之Min Stack

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.

問題連結

cpp程式碼如下:elemets如果用vector就會memory limit exceeds.以後看看deque的記憶體管理是怎樣的。

class MinStack {
private:
    deque<int> elements;
    stack<int> min_pos;
public:
    void push(int x) {
        if(elements.size()==0){
            elements.push_back(x);
            min_pos.push(0);
        }else{
            int min_=getMin();
            elements.push_back(x);
            if(x<min_)
                min_pos.push(elements.size()-1);
        }
    }

    void pop() {
        if(!elements.empty()){
            if(min_pos.top()==(int)(elements.size()-1)){
                min_pos.pop();
            }
            elements.pop_back();
        }
    }

    int top() {
        if(!elements.empty())
            return elements[elements.size()-1];
        return -1;
    }

    int getMin() {
        if(!elements.empty())
            return elements[min_pos.top()];
        return -1;
    }
};