[LeetCode]Min Stack

来源:互联网 发布:什么叫java参数传递 编辑:程序博客网 时间:2024/05/02 01:58

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.
题目意思很明确,主要问题在于查询最小元素要求O(1)

如何搜索都不可能达到O(1),所以必须在压栈和退栈的过程中维护当前的最小元素

最简单的方法是使用2个栈,一个用来维护当前的元素,一个用来维护当前的最小元素

我们直接可以使用STL的stack来内嵌2个STL栈来实现这个问题,这样我们可以得到如下方案

class MinStack {private:    stack<int>_elems;    stack<int>_minElems;public:    void push(int x) {        _elems.push(x);        if(_minElems.empty())            _minElems.push(x);        else            _minElems.push(x > _minElems.top()?_minElems.top():x);    }    void pop() {        _elems.pop();        _minElems.pop();    }    int top() {        return _elems.top();    }    int getMin() {        return _minElems.top();    }};

方法可行,问题在于LeetCode对内存有要求,这样维护2个栈,n个元素需要占用2n个空间

可以对第2个做些优化,不需要占用n个元素,当最小元素没有变化时候,不更新minStack,需要修改对应的push和pop实现

    void push(int x) {        _elems.push(x);        if(_minElems.empty()|| x <= _minElems.top()){            _minElems.push(x);        }            }    void pop() {        if(_minElems.top() == _elems.top()){            _minElems.pop();        }        _elems.pop();    }





0 0
原创粉丝点击