-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0155-min-stack.py
More file actions
34 lines (27 loc) · 748 Bytes
/
0155-min-stack.py
File metadata and controls
34 lines (27 loc) · 748 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# time complexity: O(1)
# space complexity: O(n)
class MinStack:
def __init__(self):
self.minStack = []
self.stack = []
def push(self, val: int) -> None:
self.stack.append(val)
if not self.minStack or val <= self.minStack[-1]:
self.minStack.append(val)
def pop(self) -> None:
if self.minStack[-1] == self.stack[-1]:
self.minStack.pop()
self.stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.minStack[-1]
# Your MinStack object will be instantiated and called as such:
obj = MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
print(obj.getMin())
obj.pop()
print(obj.top())
print(obj.getMin())