定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.stack.append(x)
return self.stack
def pop(self):
"""
:rtype: None
"""
val = self.stack.pop()
return val
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def min(self):
"""
:rtype: int
"""
min_val = min(self.stack)
return min_val
文章描述了一个名为MinStack的类,该类是一个数据结构,支持push、pop、top和min操作。push、pop和top操作的时间复杂度均为O(1),min函数能立即返回栈中的最小元素。在初始化时,栈为空。push方法添加元素到栈顶,pop方法移除并返回栈顶元素,top方法返回栈顶元素,而min方法返回栈中的最小元素。
354

被折叠的 条评论
为什么被折叠?



