题目:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
例子:
解题:
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.q=[]
def push(self, x):
"""
:type x: int
:rtype: void
"""
currmin = self.getMin() #插入数据的时候判断当前最小值是什么
if currmin == None or x < currmin:
currmin = x #如果当前没有最小值或是插入的数据比最小还小,就设当前为最小
self.q.append((x,currmin)) #以元组的形式插入(x,currmin)
def pop(self):
"""
:rtype: void
"""
self.q.pop()
def top(self):
"""
:rtype: int
"""
return self.q[len(self.q) - 1][0] #因为插入的是元组(x,currmin),所以top的值应该是q[][0]
def getMin(self):
"""
:rtype: int
"""
if len(self.q) == 0:
return None
else:
return self.q[len(self.q) - 1][1] b#因为插入的是元组(x,currmin),所以top的值应该是q[][1]