zoukankan      html  css  js  c++  java
  • 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.

    来自 <https://leetcode.com/problems/min-stack/description/>

    思路1:使用python自带的列表实现,然后min就用官方的min函数

       

     1 class MinStack(object):
     2 
     3     def __init__(self):
     4         """
     5         initialize your data structure here.
     6         """
     7         self.l = []
     8 
     9     def push(self, x):
    10         """
    11         :type x: int
    12         :rtype: void
    13         """
    14         self.l.append(x)
    15 
    16     def pop(self):
    17         """
    18         :rtype: void
    19         """
    20         del(self.l[-1])
    21 
    22     def top(self):
    23         """
    24         :rtype: int
    25         """
    26         return self.l[-1]
    27 
    28     def getMin(self):
    29         """
    30         :rtype: int
    31         """
    32         return min(self.l)

    思路2:发现思路1速度不理想,并且排行榜上两个块比较集中,查看后发现更好的那一种优化了min实现,在添加元素时就做了判断。

    class MinStack(object):
    
        def __init__(self):
            """
            initialize your data structure here.
            """
            self.l = []
            self.min_l = []
    
        def push(self, x):
            """
            :type x: int
            :rtype: void
            """
            self.l.append(x)
            if not len(self.min_l) or x <= self.min_l[-1]:
                self.min_l.append(x)
    
        def pop(self):
            """
            :rtype: void
            """
            if self.l[-1] == self.min_l[-1]:
                del (self.min_l[-1])
            del (self.l[-1])
    
        def top(self):
            """
            :rtype: int
            """
            return self.l[-1]
    
        def getMin(self):
            """
            :rtype: int
            """
            return self.min_l[-1]
  • 相关阅读:
    IIS日志字段详解
    Linux CPU监控指标
    PMP 质量管理新7张图
    PMP 质量管理7张图 很形象
    【MVC model 验证失效 】【Unexpected token u in JSON at position 0】【jquery-plugin-validation】
    VS 忽略文件 Git 向远程添加问题
    .Net Core 知识了解:一跨平台的奥秘
    ios 时间解析 差8个小时
    百度定位转腾讯定位
    需求评审会议分析
  • 原文地址:https://www.cnblogs.com/Thinker-pcw/p/9482148.html
Copyright © 2011-2022 走看看