class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.arr=[]
self.arr_len=0
self.min_num = 0
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.arr.append(x)
self.arr_len = self.arr_len + 1
if self.arr_len == 1:
self.min_num = x
else:
if self.min_num > x:
self.min_num = x
def pop(self):
"""
:rtype: void
"""
if self.arr_len > 0:
top_v=self.arr[self.arr_len - 1]
self.arr = self.arr[:self.arr_len-1]
self.arr_len = self.arr_len - 1
if self.arr_len == 0:
self.min_num = 0
if self.min_num == top_v and self.arr_len > 0:
self.min_num = self.arr[0]
for v in self.arr[1:]:
if self.min_num > v:
self.min_num = v
def top(self):
"""
:rtype: int
"""
if self.arr_len > 0:
return self.arr[self.arr_len - 1]
def getMin(self):
"""
:rtype: int
"""
return self.min_num
# 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()
Min Stack
May 28, 2017