• 15-155. Min Stack


    题目描述:

    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.

    Example:

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

    代码:

     1 class MinStack(object):
     2 
     3     def __init__(self):
     4         """
     5         initialize your data structure here.
     6         """
     7         self.stack = [] # 如果这个stack想在整个class中都可以使用,则必须要加上self.
     8 
     9     def push(self, x):
    10         """
    11         :type x: int
    12         :rtype: None
    13         """
    14         curMin = self.getMin()
    15         if curMin == None or x < curMin:
    16             curMin = x
    17         self.stack.append((x, curMin))
    18 
    19     def pop(self):
    20         """
    21         :rtype: None
    22         """
    23         self.stack.pop()
    24 
    25     def top(self):
    26         """
    27         :rtype: int
    28         """
    29         return self.stack[-1][0] if self.stack else None
    30 
    31     def getMin(self):
    32         """
    33         :rtype: int
    34         """
    35         return self.stack[-1][1] if self.stack else None
    36 
    37 
    38 # Your MinStack object will be instantiated and called as such:
    39 # obj = MinStack()
    40 # obj.push(x)
    41 # obj.pop()
    42 # param_3 = obj.top()
    43 # param_4 = obj.getMin()

    分析:

    1. python的栈、链表、树都是用list实现的。

    2. 如果一个在class内部定义的变量想要在整个类中都可以使用,则这个变量的前面必须加上self. 。

  • 相关阅读:
    Ubuntu 或 UbuntuKyLin14.04 Unity桌面側边栏和顶层菜单条显示异常解决方法
    关于程序猿的几个阶段!
    独立开发人员低成本推广APP的18条技巧
    Effective C++ 条款27
    OpensStack instance debug
    OpenStackCLI调试及术语识记
    OpenStack术语名词及问题调试
    apacheOfbiz
    obiz
    How to run OFBiz as a Service on linux
  • 原文地址:https://www.cnblogs.com/tbgatgb/p/10970929.html
Copyright © 2020-2023  润新知