题目描述:
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.
Example:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> Returns -3. minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2.
代码:
1 class MinStack(object): 2 3 def __init__(self): 4 """ 5 initialize your data structure here. 6 """ 7 self.stack = [] # 如果这个stack想在整个class中都可以使用,则必须要加上self. 8 9 def push(self, x): 10 """ 11 :type x: int 12 :rtype: None 13 """ 14 curMin = self.getMin() 15 if curMin == None or x < curMin: 16 curMin = x 17 self.stack.append((x, curMin)) 18 19 def pop(self): 20 """ 21 :rtype: None 22 """ 23 self.stack.pop() 24 25 def top(self): 26 """ 27 :rtype: int 28 """ 29 return self.stack[-1][0] if self.stack else None 30 31 def getMin(self): 32 """ 33 :rtype: int 34 """ 35 return self.stack[-1][1] if self.stack else None 36 37 38 # Your MinStack object will be instantiated and called as such: 39 # obj = MinStack() 40 # obj.push(x) 41 # obj.pop() 42 # param_3 = obj.top() 43 # param_4 = obj.getMin()
分析:
1. python的栈、链表、树都是用list实现的。
2. 如果一个在class内部定义的变量想要在整个类中都可以使用,则这个变量的前面必须加上self. 。