Completes all test cases
This commit is contained in:
parent
085299d955
commit
18baee9bd5
63
NeetCodeRoadmap/Stack/155_Min_Stack.py
Normal file
63
NeetCodeRoadmap/Stack/155_Min_Stack.py
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
class MinStack(object):
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.st=[] #stack
|
||||||
|
self.min=None #min element
|
||||||
|
|
||||||
|
def push(self, val):
|
||||||
|
"""
|
||||||
|
:type val: int
|
||||||
|
:rtype: None
|
||||||
|
"""
|
||||||
|
if len(self.st)==0:
|
||||||
|
self.st.append(val)
|
||||||
|
self.min=val
|
||||||
|
else:
|
||||||
|
if val>=self.min:
|
||||||
|
self.st.append(val)
|
||||||
|
else:
|
||||||
|
self.st.append(2*val-self.min)
|
||||||
|
self.min=val
|
||||||
|
|
||||||
|
def pop(self):
|
||||||
|
"""
|
||||||
|
:rtype: None
|
||||||
|
"""
|
||||||
|
x=self.st.pop()
|
||||||
|
if x<self.min:
|
||||||
|
self.min=2*self.min-x
|
||||||
|
|
||||||
|
def top(self):
|
||||||
|
"""
|
||||||
|
:rtype: int
|
||||||
|
"""
|
||||||
|
x=self.st[-1]
|
||||||
|
if x>=self.min:
|
||||||
|
return x
|
||||||
|
return self.min
|
||||||
|
|
||||||
|
|
||||||
|
def getMin(self):
|
||||||
|
"""
|
||||||
|
:rtype: int
|
||||||
|
"""
|
||||||
|
return self.min
|
||||||
|
|
||||||
|
|
||||||
|
minStack = MinStack()
|
||||||
|
minStack.push(-2)
|
||||||
|
minStack.push(0)
|
||||||
|
minStack.push(-3)
|
||||||
|
minStack.getMin() # return -3
|
||||||
|
minStack.pop()
|
||||||
|
minStack.top() # return 0
|
||||||
|
minStack.getMin() # return -2
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Your MinStack object will be instantiated and called as such:
|
||||||
|
# obj = MinStack()
|
||||||
|
# obj.push(val)
|
||||||
|
# obj.pop()
|
||||||
|
# param_3 = obj.top()
|
||||||
|
# param_4 = obj.getMin()
|
||||||
Loading…
Reference in New Issue
Block a user