zoukankan      html  css  js  c++  java
  • leetcode-easy-design-155 Min Stack

    mycode   21.48%

    class MinStack(object):
    
        def __init__(self):
            """
            initialize your data structure here.
            """
            self.res = []
            
    
        def push(self, x):
            """
            :type x: int
            :rtype: None
            """
            self.res.append(x)
            
    
        def pop(self):
            """
            :rtype: None
            """
            if not self.res:
                return None
            else:
                val = self.res[-1]
                self.res[:] = self.res[:-1]
                return val
            
    
        def top(self):
            """
            :rtype: int
            """
            if not self.res:
                return None
            else:
                return self.res[-1]
          
            
    
        def getMin(self):
            """
            :rtype: int
            """
            if not self.res:
                return None
            else:
                return min(self.res)
          
            
    
    
    # Your MinStack object will be instantiated and called as such:
    # obj = MinStack()
    # obj.push(x)
    # obj.pop()
    # param_3 = obj.top()
    # param_4 = obj.getMin()

    列表是有pop操作的

      self.res.pop()

    参考

    始终更新最小值,所以节省 了时间

    class MinStack(object):
    
        def __init__(self):
            """
            initialize your data structure here.
            """
            self.stack = []
            self.minval = 99999999999999999
    
        def push(self, x):
            """
            :type x: int
            :rtype: None
            """
            if(x < self.minval):
                self.minval = x
            self.stack.append(x)
    
        def pop(self):
            """
            :rtype: None
            """
            if(self.stack[-1] == self.minval):
                self.minval = 99999999999
                for num in self.stack[0:-1]:
                    if(num < self.minval):
                        self.minval = num
            self.stack.pop(-1)
    
        def top(self):
            """
            :rtype: int
            """
            return self.stack[-1]
    
        def getMin(self):
            """
            :rtype: int
            """
            return self.minval
    
    
    # Your MinStack object will be instantiated and called as such:
    # obj = MinStack()
    # obj.push(x)
    # obj.pop()
    # param_3 = obj.top()
    # param_4 = obj.getMin()
  • 相关阅读:
    MYSQL 字符串操作
    关于IT企业组织架构的一些思考
    关于《Java封面》一些感想
    浏览器缓存资源文件的问题
    为什么《一个程序员怎么能做出这样的事情》?
    TCP/IP协议中的参数说明
    java编译器对代码的优化
    事务属性小结
    事务的编程模型
    从阿里云os和Google之争看开源协议
  • 原文地址:https://www.cnblogs.com/rosyYY/p/11003635.html
Copyright © 2011-2022 走看看