LintCode Q12 Min Stack 2stack 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
34
35
36
37
class MinStack(object):
def __init__(self):
# do some intialize if necessary
# Total Runtime: 344 ms
# 100% test cases passed.
self._stack = []
self._min_stack = []
def push(self, number):
# write yout code here
len_stack = len(self._stack)
if len_stack == 0:
self._min_stack.append(number)
else:
min_num = self._min_stack[-1]
if number <= min_num:
self._min_stack.append(number)
self._stack.append(number)
def pop(self):
# pop and return the top item in stack
len_stack = len(self._stack)
if len_stack < 1:
return None
num = self._stack.pop()
if num == self._min_stack[-1]:
self._min_stack.pop()
return num
def min(self):
# return the minimum number in stack
len_stack = len(self._stack)
if len_stack < 1:
return None
return self._min_stack[-1]
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。