zoukankan      html  css  js  c++  java
  • 包含main函数的栈

    题目描述

    定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

    解答

    方法一:两个栈实现

    # coding:utf-8
    
    class Solution:
        def __init__(self):
            self.a = []
            self.b = []
        def push(self, node):
            # write code here
            self.a.insert(0, node)
        def pop(self):
            # write code here
            while self.a:
                self.b.append(self.a.pop())
            return self.b.pop()
        def top(self):
            # write code here
            return self.b[-1]
        def min(self):
            # write code here
            while self.a:
                self.b.append(self.a.pop())
            return min(self.b)
    
    p = Solution()
    p.push(3)
    p.push(12)
    p.push(13)
    # print p.pop()
    # print p.pop()
    p.push(2)
    # print p.pop()
    # print p.pop()
    p.pop()
    print p.min()

    方法二:还是两个栈实现

    class Solution:
        def __init__(self):
            self.a = []
            self.b = []
        def push(self, node):
            self.a.append(node)
            if len(self.b) == 0 or node <= self.b[-1]:
                self.b.append(node)
            else:
                self.b.append(self.b[-1])
        def pop(self):
            if self.a:
                self.b.pop()
                return self.a.pop()
        def top(self):
            # write code here
            return self.a[-1]
        def min(self):
            # write code here
            if self.b:
                return self.b[-1]
    
    p = Solution()
    p.push(3)
    p.push(12)
    p.push(13)
    # print p.pop()
    # print p.pop()
    p.push(2)
    # print p.pop()
    # print p.pop()
    print p.min()

    结束!

  • 相关阅读:
    php的四种算法
    laravel框架安装过程中遇到的问题
    json_decode转码无效
    php通过mysqli链接mysql数据库
    jq函数绑定与解绑
    redis的运行机制
    数据库设计的三范式
    MYSQL数据库索引
    PHP超全局变量数组
    vue的settings.json格式化配置
  • 原文地址:https://www.cnblogs.com/aaronthon/p/13787766.html
Copyright © 2011-2022 走看看