设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。(第一个我写的,但是在获取最小值上面时间耗时太久了)
class MinStack1(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.stack_copy = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
if x is not None:
self.stack.append(x)
self.stack_copy.append(x)
def pop(self):
"""
:rtype: None
"""
if self.stack:
self.stack_copy.remove(self.stack.pop())
def top(self):
"""
:rtype: int
"""
if self.stack:
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
if self.stack:
return sorted(self.stack_copy)[0]
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
"""
self.stack.append(x)
if len(self.min_stack) == 0:
self.min_stack.append(x)
else:
if self.min_stack[-1] >= x:
self.min_stack.append(x)
def pop(self):
"""
:rtype: None
"""
x = self.stack.pop()
if x == self.min_stack[-1]:
self.min_stack.pop()
return x
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.min_stack[-1]
if __name__ == '__main__':
s1 = MinStack()
s1.push(-2)
s1.push(0)
s1.push(-10)
s1.push(-3)
print(s1.getMin())
s1.pop()
print(s1.top())
print(s1.getMin())