-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
716_Max_Stack.py
56 lines (50 loc) · 1.19 KB
/
716_Max_Stack.py
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
class MaxStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.max_stack = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack.append(x)
if len(self.max_stack) == 0:
self.max_stack.append(x)
return
if self.max_stack[-1] > x:
self.max_stack.append(self.max_stack[-1])
else:
self.max_stack.append(x)
def pop(self):
"""
:rtype: int
"""
if len(self.stack) != 0:
self.max_stack.pop(-1)
return self.stack.pop(-1)
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def peekMax(self):
"""
:rtype: int
"""
if len(self.max_stack) != 0:
return self.max_stack[-1]
def popMax(self):
"""
:rtype: int
"""
val = self.peekMax()
buff = []
while self.top() != val:
buff.append(self.pop())
self.pop()
while len(buff) != 0:
self.push(buff.pop(-1))
return val