LeetCode-155.Min Stack

来源:互联网 发布:重庆行知教育集团 编辑:程序博客网 时间:2024/04/30 12:31

https://leetcode.com/problems/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.

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:    stack<int> s, minS;    int minVal = 2147483647;    /** initialize your data structure here. */    MinStack()     {             }        void push(int x)     {        s.push(x);    if (x < minVal)    minVal = x;    minS.push(minVal);    }        void pop()     {        s.pop();    minS.pop();    if(s.empty())    minVal = 2147483647;else    minVal = minS.top();    }        int top()     {        return s.top();    }        int getMin()     {        if (s.empty())    return 2147483647;    else    return minS.top();    }};

也可以不使用minVal,事先在最小值栈底存放2147483647

class MinStack{public:    stack<int> s, minS;    /** initialize your data structure here. */    MinStack()     {        minS.push(2147483647);    }        void push(int x)     {        s.push(x);    if (x < minS.top())    minS.push(x);    else    minS.push(minS.top());    }        void pop()     {        s.pop();    minS.pop();    }        int top()     {        return s.top();    }        int getMin()     {        return minS.top();    }};

只用一个栈实现 参考https://leetcode.com/discuss/21071/java-accepted-solution-using-one-stack

class MinStack{public:    stack<int> s;    int minVal = 2147483647;    /** initialize your data structure here. */    MinStack()     {    }        void push(int x)     {       if (x <= minVal)    {    s.push(minVal);    minVal = x;    }    s.push(x);    }        void pop()     {        if (minVal == s.top())    {    s.pop();    minVal = s.top();    }    s.pop();    //if (s.empty())    //minVal = 2147483647;    }        int top()     {        return s.top();    }        int getMin()     {        return minVal;    }};



0 0
原创粉丝点击