LintCode Q12 Min Stack in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2016年11月6日
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
class MinStack(object):
def __init__(self):
# do some intialize if necessary
# Total Runtime: 349 ms
# 100% test cases passed.
self._stack = []
def push(self, number):
# write yout code here
len_stack = len(self._stack)
if len_stack == 0:
min_num = number
else:
min_num = min(number, self._stack[-1][1])
self._stack.append((number, min_num))
def pop(self):
# pop and return the top item in stack
if len(self._stack) > 0:
(num, min_num) = self._stack.pop()
else:
num = None
return num
def min(self):
# return the minimum number in stack
len_stack = len(self._stack)
if len_stack > 0:
(num, min_num) = self._stack[-1]
else:
min_num = None
return min_num
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。