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.
来自 <https://leetcode.com/problems/min-stack/description/>
思路1:使用python自带的列表实现,然后min就用官方的min函数
1 class MinStack(object): 2 3 def __init__(self): 4 """ 5 initialize your data structure here. 6 """ 7 self.l = [] 8 9 def push(self, x): 10 """ 11 :type x: int 12 :rtype: void 13 """ 14 self.l.append(x) 15 16 def pop(self): 17 """ 18 :rtype: void 19 """ 20 del(self.l[-1]) 21 22 def top(self): 23 """ 24 :rtype: int 25 """ 26 return self.l[-1] 27 28 def getMin(self): 29 """ 30 :rtype: int 31 """ 32 return min(self.l)
思路2:发现思路1速度不理想,并且排行榜上两个块比较集中,查看后发现更好的那一种优化了min实现,在添加元素时就做了判断。
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.l = [] self.min_l = [] def push(self, x): """ :type x: int :rtype: void """ self.l.append(x) if not len(self.min_l) or x <= self.min_l[-1]: self.min_l.append(x) def pop(self): """ :rtype: void """ if self.l[-1] == self.min_l[-1]: del (self.min_l[-1]) del (self.l[-1]) def top(self): """ :rtype: int """ return self.l[-1] def getMin(self): """ :rtype: int """ return self.min_l[-1]