定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
提示:
各函数的调用总次数不超过 20000 次
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack=[]
self.min_stack=[]
def push(self, x):
"""
:type x: int
:rtype: None
"""
if not self.min_stack or x<=self.min_stack[-1]:
self.min_stack.append(x)
self.stack.append(x)
def pop(self):
"""
:rtype: None
"""
tmp=self.stack.pop()
if tmp==self.min_stack[-1]:
self.min_stack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def min(self):
"""
:rtype: int
"""
if not self.min_stack:
return None
return self.min_stack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.min()
执行结果:
通过
显示详情
执行用时 :132 ms, 在所有 Python 提交中击败了94.79%的用户
内存消耗 :16.3 MB, 在所有 Python 提交中击败了100.00%的用户