面试题30:包含min函数的栈

包含min函数的栈

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数。
min、push、pop都为O(1)

借助一个辅助栈,每次新来一个元素,如果比当前最小值大,则将当前最小值压栈。否则更改。
pop时也同时pop掉辅助栈

leetcode

  1. 最小栈
    设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
class MinStack {
public:
    stack<int>numbers;
    stack<int>minstack;
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        numbers.push(x);
        if(minstack.empty())
        {
            minstack.push(x);
        }
        else
        {
            if(minstack.top() < x)
            {
                minstack.push(minstack.top());
            }
            else
            {
                minstack.push(x);
            }
        }
    }
    
    void pop() {
        numbers.pop();
        minstack.pop();
    }
    
    int top() {
        return numbers.top();
    }
    
    int getMin() {
        return minstack.top();
    }
};

/**
 * 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();
 */

执行用时 : 36 ms, 在Min Stack的C++提交中击败了99.09% 的用户
内存消耗 : 17 MB, 在Min Stack的C++提交中击败了39.35% 的用户

发布了68 篇原创文章 · 获赞 2 · 访问量 6183

猜你喜欢

转载自blog.csdn.net/qq_30050175/article/details/90579159
今日推荐