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.
The following method can’t do retrieving the minimum element in constant time.
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.myStack = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.myStack.append(x)
def pop(self):
"""
:rtype: None
"""
self.myStack.pop()
def top(self):
"""
:rtype: int
"""
return self.myStack[-1]
def getMin(self):
"""
:rtype: int
"""
return min(self.myStack)
# 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()
```python
## another way to do instead of using list, but use tuple or linked list.
## change the getMin() time from linear to constant time
class MinStack(object):
def __init__(self):
self.stack = []
def push(self, x):
self.stack.append((x, min(self.getMin(), x)))
##every stack contains x and the current MinValue in the whole stack after pushing x
def pop(self):
self.stack.pop()
def top(self):
if self.stack:
return self.stack[-1][0]
def getMin(self):
if self.stack:
return self.stack[-1][1]
return sys.maxint