forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmax-stack.py
More file actions
37 lines (23 loc) · 710 Bytes
/
max-stack.py
File metadata and controls
37 lines (23 loc) · 710 Bytes
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
#https://leetcode.com/problems/max-stack/
#peekMax() and popMax() are O(N)
#Else are O(1)
class MaxStack(object):
def __init__(self):
self.stack = []
def push(self, x):
self.stack.append(x)
def pop(self):
return self.stack.pop()
def top(self):
return self.stack[-1]
def peekMax(self):
return max(self.stack)
def popMax(self):
max_num = None
max_index = None
for i in range(len(self.stack)):
num = self.stack[i]
if num>=max_num:
max_num = num
max_index = i
return self.stack.pop(max_index)