-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMinStack.py
More file actions
51 lines (40 loc) · 1 KB
/
MinStack.py
File metadata and controls
51 lines (40 loc) · 1 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://oj.leetcode.com/problems/min-stack/
"""
class MinStack:
def __init__(self):
self._stack = []
self._min_index = []
# @param x, an integer
# @return an integer
def push(self, x):
try:
if x < self.getMin():
self._min_index.append(len(self._stack))
except:
self._min_index.append(0)
self._stack.append(x)
# @return nothing
def pop(self):
self._stack.pop()
if self._min_index[-1] >= len(self._stack):
self._min_index.pop()
# @return an integer
def top(self):
return self._stack[-1]
# @return an integer
def getMin(self):
return self._stack[self._min_index[-1]]
def __str__(self):
return "%s, %s" % (self._stack, self._min_index)
if __name__ == '__main__':
st = MinStack()
st.push(100)
print(st)
st.push(1)
print(st)
st.push(34)
print(st)
print(st.getMin())