包含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()
复制代码

结束!

posted @   aaronthon  阅读(201)  评论(0编辑  收藏  举报
编辑推荐:
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
阅读排行:
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法
历史上的今天:
2019-10-09 js生成二维码
2018-10-09 什么是进程?什么是线程?进程和线程之间的区别是什么?
点击右上角即可分享
微信分享提示