题目
Design a stack that supports push, pop, top, and retrievingthe 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:
def __init__(self):
self.L=[]
def pop(self):
return self.L.pop()
def push(self,x):
self.L.append(x)
def top(self):
return self.L[-1]
def getMin(self):
tmpL = self.L[:]
tmpL.sort()
return tmpL[0]
每次提示答案都超时…表吐槽,表示刚学python