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.
最初步的思路就是用list,插入和删除新数据很方便,但是在检索最小值的时候运行时间大吓人。
考虑优化思路:在插入新数据的时候进行对比,这个试了几种方法,比如增加一个列表来保存最小值和索引,但是每当列表中元素有变动的时候,索引都会改变,这种太麻烦因此pass掉了这种方式。
在论坛中有一种方法,将插入的元素和插入动作后当前stack元素中的最小值保存在元组中。因为stack是后进先出,这样在移除最上层的元素时,不用重新loop就可以提取top-1的最小值。
以下代码runtime=80ms,如果将insert改为append,runtime=53ms。
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
# use list as data type
self.stack = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
curr_min = self.getMin()
if curr_min == None:
curr_min = x
else:
curr_min = min(curr_min,x)
self.stack.insert(0,(x,curr_min))
def pop(self):
"""
:rtype: void
"""
self.stack.pop(0)
def top(self):
"""
:rtype: int
"""
return self.stack[0][0]
def getMin(self):
"""
:rtype: int
"""
if len(self.stack) == 0:
return None
return self.stack[0][1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
参考:https://leetcode.com/problems/min-stack/discuss/49022/My-Python-solution