题解 | #包含min函数的栈#

包含min函数的栈

https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49

# -*- coding:utf-8 -*-
# """
# method_1: 一种可以接受的方法
# """
# class Solution:
#     def __init__(self):
#         self.stack1 = list()
#     def push(self, node):
#         # write code here
#         # print("node: ", node)
#         self.stack1.append(node)
#         print("after append: ", self.stack1)
#         pass
#     def pop(self):
#         # write code here
#         if len(self.stack1) == None:
#             return -1
#         rst = self.stack1.pop()
#         print("pop result: ", rst)
#         pass
#     def top(self):
#         # write code here
#         if len(self.stack1) == None:
#             return -1
#         rst = self.stack1[-1]
#         print("top: ", rst)
#         return rst
#         pass
#     def min(self):
#         # write code here
#         max_val = 0
#         min_val = self.stack1[0]
#         for i in range(len(self.stack1)):
#             tmp = self.stack1[i]
#             if max_val < tmp:
#                 max_val = tmp
#             elif min_val >= tmp:
#                 min_val = tmp

#         print("min val: ", min_val)
#         return min_val
#         pass

"""
method_2: office method
"""
class Solution:
    def __init__(self):
        self.stack1 = list()
        self.stack2 = list()

    def push(self, node):
        self.stack1.append(node)
        
        # 空或新元素较小,则入stack2
        if len(self.stack2) == 0 or self.stack2[-1] > node:
            self.stack2.append(node)
        else:
            self.stack2.append(self.stack2[-1])
        pass

    def pop(self):
        self.stack1.pop()
        self.stack2.pop()
        pass

    def top(self):
        return self.stack1[-1]
        pass

    def min(self):
        return self.stack2[-1]
        pass

    
	提供两种方法,method1 是自己想出来的思路和解决办法; method2 是官方推荐思路和办法,该题解决思路和上一题类似。

全部评论

相关推荐

卡bg这么严,不是92真是太难了
投递芯原微电子(上海)股份有限公司等公司10个岗位
点赞 评论 收藏
分享
06-19 19:06
门头沟学院 Java
码农索隆:别去东软,真学不到东西,真事
点赞 评论 收藏
分享
08-05 11:30
湘潭大学 营销
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务