导航

LeetCode 155. Min Stack

Posted on 2016-08-07 20:02  CSU蛋李  阅读(119)  评论(0编辑  收藏  举报

这个题目的关键是要有一个最小值的私有变量,在入栈和出栈时检查一下最小值是否变化即可,就能实现返回最小值是在常数时间内

 

不过题目的注释中是有错误的,因为用new得到的是一个指针,不能用.运算符而是用->运算符

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.
class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        mytop = 0;
        min = INT32_MAX;
    }

    void push(int x) {
        ++mytop;
        myarray.insert(myarray.cend(),x);
        if (min > x)
            min = x;
    }

    void pop() {
        --mytop;
        if (min == myarray[mytop])
        {
            min=myarray[0];
            for(int i=1;i<mytop;++i)
            {
                if(min>myarray[i])
                min=myarray[i];
            }
        }
        if(mytop==0)
        min = INT32_MAX;
        myarray.erase(--myarray.end());
    }

    int top() {
        return myarray[mytop-1];
    }

    int getMin() {
        return min;
    }
private:
    int mytop;
    int min;
    vector<int> myarray;
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */