forked from super30admin/Design-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminStack.py
More file actions
45 lines (29 loc) · 937 Bytes
/
minStack.py
File metadata and controls
45 lines (29 loc) · 937 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
35
36
37
38
39
40
41
42
43
44
45
#Time Complexity = O(1)
#Space Complexity = O(n)
from collections import deque
class MinStack:
def __init__(self):
self.mainStack = deque()
self.minStack = deque()
def push(self, val: int) -> None:
self.mainStack.append(val)
if not self.minStack:
self.minStack.append(val)
else:
if self.minStack[-1] >= val:
self.minStack.append(val)
def pop(self) -> None:
topElement = self.mainStack.pop()
if topElement == self.minStack[-1]:
self.minStack.pop()
return topElement
def top(self) -> int:
return self.mainStack[-1]
def getMin(self) -> int:
return self.minStack[-1]
# 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()