• 155_最小栈


    最小栈

    题目

    设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

    • push(x) – 将元素 x 推入栈中。
    • pop() – 删除栈顶的元素。
    • top() – 获取栈顶元素。
    • getMin() – 检索栈中的最小元素。
      示例:
    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.getMin();   --> 返回 -3.
    minStack.pop();
    minStack.top();      --> 返回 0.
    minStack.getMin();   --> 返回 -2.
    

    思路

    这个题要求在常数时间内获得最小值,因此不能在getMin()的时候再去计算,应该在push的时候就计算了。

    可以用一个栈,这个栈保存的是每个数字进入栈的时候的(值与最小值)。速度很快。

    答案

    class MinStack(object):
    
        def __init__(self):
            """
            initialize your data structure here.
            """
            self.stack = []
            
    
        def push(self, x):
            """
            :type x: int
            :rtype: void
            """
            if not self.stack:
                self.stack.append((x, x))
            else:
                self.stack.append((x, min(x, self.stack[-1][1])))
            
    
        def pop(self):
            """
            :rtype: void
            """
            self.stack.pop()
            
    
        def top(self):
            """
            :rtype: int
            """
            return self.stack[-1][0]
            
    
        def getMin(self):
            """
            :rtype: int
            """
            return self.stack[-1][1]
    
    欢迎,关注我的公众号 “DailyProgrammer”,每天8点为你推送精彩的技术文章!!!
  • 相关阅读:
    js点击按钮触发事件的方法(含函数的写法)
    操作文件
    克隆别人的仓库,提交到自己的远程仓库的方法
    时间戳变成 标准时间展示的方法
    还没看的书
    print 和 println的区别
    初学java记录
    java 的一个hellow word 代码解释
    eclipse 创建一个java项目 运行
    Eclipse环境配置
  • 原文地址:https://www.cnblogs.com/dailyprogrammer/p/12241631.html
Copyright © 2020-2023  润新知