LeetCode Min Stack

来源:互联网 发布:网络是利与弊 编辑:程序博客网 时间:2024/05/01 00:24

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> s1;    stack<int> ms;    void push(int x) {        if(!s1.empty())        {            int temp = ms.top();            if(temp>x)                ms.push(x);            else                ms.push(temp);            s1.push(x);        }else        {            s1.push(x);            ms.push(x);        }    }    void pop() {        s1.pop();        ms.pop();    }    int top() {        return s1.top();    }    int getMin() {        return ms.top();    }};


0 0
原创粉丝点击