【leetcode-python-6】155. 最小栈
渣渣原始版(96.26%)
一个栈实现普通栈的功能,另一个栈用来存最小值。
有考虑过“哨兵”,算是进步。后面加了哨兵试了下,是90.63%。
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.minstack = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
if not self.stack or self.minstack[-1] >= x:
self.minstack.append(x)
self.stack.append(x)
def pop(self):
"""
:rtype: None
"""
if self.stack[-1] == self.minstack[-1]:
self.minstack.pop()
self.stack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.minstack[-1]
参考官方版(70.46%)
官方用了“哨兵”。每次都比较最小的,把最小的append上,所以每次都做了append操作,可能是比判断慢吧。
注:参考题解区官方思路。
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.minstack = [float('inf')]
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.stack.append(x)
self.minstack.append(min(x, self.minstack[-1]))
def pop(self):
"""
:rtype: None
"""
self.minstack.pop()
self.stack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.minstack[-1]
新手入坑,多多包涵~~