题目
栈:先入后出
刚拿到这道题感觉和之前一道类似用两个栈实现队列
因此这个题实现起来,尤其是在求最小值时,使用python内置函数简直暴力
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
def push(self, node):
# write code here
self.stack.append(node)
def pop(self):
# write code here
self.stack.pop()
def top(self):
# write code here
if self.stack:
return self.stack[-1]
def min(self):
# write code here
return min(self.stack)
运行成功后,看讨论区遇到了一个比较高级一点的解法:利用一个辅助的栈将每次入栈、出栈操作后的当前站内的最小值保留下来。
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
#用于存储栈中当时的最小值
self.stack_min = []
def push(self, node):
# write code here
self.stack.append(node)
#有新元素入栈stack时,需要将此时最下的元素入栈到stack_min
if not self.stack_min:
self.stack_min.append(node)
elif node < self.stack_min[-1]:
self.stack_min.append(node)
else:
self.stack_min.append(self.stack_min[-1])
def pop(self):
# write code here
self.stack.pop()
#将对应的最小值出栈
self.stack_min.pop()
def top(self):
# write code here
if self.stack:
return self.stack[-1]
def min(self):
# write code here
#只需要将stack_min中最后一个元素出栈即可
return self.stack_min[-1]