zoukankan      html  css  js  c++  java
  • 150-155. 最小栈

    设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。(第一个我写的,但是在获取最小值上面时间耗时太久了)
    class MinStack1(object):
    
        def __init__(self):
            """
            initialize your data structure here.
            """
            self.stack = []
            self.stack_copy = []
    
        def push(self, x):
            """
            :type x: int
            :rtype: None
            """
            if x is not None:
                self.stack.append(x)
                self.stack_copy.append(x)
    
        def pop(self):
            """
            :rtype: None
            """
            if self.stack:
                self.stack_copy.remove(self.stack.pop())
    
        def top(self):
            """
            :rtype: int
            """
            if self.stack:
                return self.stack[-1]
    
        def getMin(self):
            """
            :rtype: int
            """
            if self.stack:
                return sorted(self.stack_copy)[0]
    
    
    class MinStack(object):
    
        def __init__(self):
            """
            initialize your data structure here.
            """
            self.stack = []
            self.min_stack = []
    
        def push(self, x):
            """
            :type x: int
            :rtype: None
            """
            self.stack.append(x)
            if len(self.min_stack) == 0:
                self.min_stack.append(x)
            else:
                if self.min_stack[-1] >= x:
                    self.min_stack.append(x)
    
        def pop(self):
            """
            :rtype: None
            """
            x = self.stack.pop()
            if x == self.min_stack[-1]:
                self.min_stack.pop()
            return x
    
        def top(self):
            """
            :rtype: int
            """
            return self.stack[-1]
    
        def getMin(self):
            """
            :rtype: int
            """
            return self.min_stack[-1]
    
    
    if __name__ == '__main__':
        s1 = MinStack()
        s1.push(-2)
        s1.push(0)
        s1.push(-10)
        s1.push(-3)
        print(s1.getMin())
        s1.pop()
        print(s1.top())
        print(s1.getMin())
    
  • 相关阅读:
    Intel的cpu虚拟化
    [转]深入理解Kingfisher(下)
    [转]深入理解Kingfisher(上)
    [转]Xcode中TimeProfile的使用
    [汇]编译错误汇总
    [汇]我常去逛的iOS干货文章、blog等
    [转]UICollectionView 全解
    [转]iOS 保持界面流畅的技巧
    [转]Swift 基于 willSet & didSet 的订阅block(Observable)
    IOS开发之UIScrollViewDelegate详解
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14302620.html
Copyright © 2011-2022 走看看