美文网首页
【剑指 offer】包含min函数的栈

【剑指 offer】包含min函数的栈

作者: 邓泽军_3679 | 来源:发表于2019-04-12 22:56 被阅读0次

    1、题目描述

    设计一个支持push,pop,top等操作并且可以在O(1)时间内检索出最小元素的堆栈。

    • push(x)–将元素x插入栈中
    • pop()–移除栈顶元素
    • top()–得到栈顶元素
    • getMin()–得到栈中最小元素

    样例

    MinStack minStack = new MinStack();
    minStack.push(-1);
    minStack.push(3);
    minStack.push(-4);
    minStack.getMin(); --> Returns -4.
    minStack.pop();
    minStack.top(); --> Returns 3.
    minStack.getMin(); --> Returns -1.

    2、问题描述:

    • 具有栈的基本功能外,能够返回栈的最小值。

    3、问题关键:

    • 单调栈,维护一个单调栈,返回最小值。
    • 对于单调栈,如果当前压入的元素=栈顶元素也需要压入,因为可能有两个相同的元素。

    4、C++代码:

    class MinStack {
    public:
        /** initialize your data structure here. */
        stack<int> stk1, stk2;
        MinStack() {
        }
        void push(int x) {
            stk1.push(x);
            if (stk2.empty() || x <= stk2.top())  {
                stk2.push(x);
            }
        }
        void pop() {
            int tmp = stk1.top();
            stk1.pop();
            if (tmp == stk2.top()) 
            stk2.pop();
        } 
        int top() {
            return stk1.top();
        }
        int getMin() {
            return stk2.top();
        }
    };
    

    相关文章

      网友评论

          本文标题:【剑指 offer】包含min函数的栈

          本文链接:https://www.haomeiwen.com/subject/ebhkwqtx.html