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()

    结束!

  • 相关阅读:
    wxpython的安装

    拓扑排序
    树,二叉树,森林,三者的转换
    二叉树的遍历
    最短路径
    图的遍历
    图的最小生成树
    哈夫曼树的应用
    哈夫曼树
  • 原文地址:https://www.cnblogs.com/aaronthon/p/13787766.html
Copyright © 2011-2022 走看看