-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path155_1.py
More file actions
45 lines (36 loc) · 1.08 KB
/
155_1.py
File metadata and controls
45 lines (36 loc) · 1.08 KB
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
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min_stack = []
def push(self, x: int) -> None:
if not self.stack:
self.stack.append(x)
self.min_stack.append((x, 1))
return
minimum, count = self.min_stack[-1]
if x < minimum:
self.min_stack.append((x, 1))
elif x == minimum:
self.min_stack[-1] = (x, count + 1)
self.stack.append(x)
def pop(self) -> None:
x = self.stack.pop()
minimum, count = self.min_stack[-1]
if x == minimum:
if count > 1:
self.min_stack[-1] = (x, count - 1)
else:
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1][0]
# 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()