-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path021-min-stack.py
More file actions
65 lines (47 loc) · 1.19 KB
/
021-min-stack.py
File metadata and controls
65 lines (47 loc) · 1.19 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class MinStack:
def __init__(self):
self.stack = []
self.mins = []
def push(self, x: int) -> None:
self.stack.append(x)
if not self.mins:
self.mins.append(x)
return
if x <= self.mins[-1]:
self.mins.append(x)
def pop(self) -> None:
e = self.stack.pop()
if self.mins[-1] == e:
self.mins.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.mins[-1]
class MinStack2:
def __init__(self):
self.stack = []
def push(self, x: int) -> None:
current_min = self.getMin()
if current_min is None or x < current_min:
current_min = x
self.stack.append((x, current_min))
def pop(self) -> None:
self.stack.pop()
def top(self) -> int:
return self.stack[-1][0]
def getMin(self) -> int:
if not self.stack:
return None
return self.stack[-1][1]
minStack = MinStack()
minStack.push(0)
minStack.push(1)
minStack.push(0)
m = minStack.getMin()
print(m)
# // return -3
minStack.pop()
# // return 0
t = minStack.getMin()
print(t)
# // return -2