-
Notifications
You must be signed in to change notification settings - Fork 0
/
239_sliding_window_maximum.py
40 lines (34 loc) · 1.01 KB
/
239_sliding_window_maximum.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
class MonotonicQueue(object):
def __init__(self):
self.list = [] # a dummy deque
self.head = 0 # mark the front of the deque
self.tail = -1
def get_max(self):
return self.list[self.head]
def push(self, n):
while self.list and self.tail >= self.head and self.list[-1] < n :
self.tail -= 1
del self.list[-1]
self.list.append(n)
self.tail += 1
def pop(self, n):
if self.list and self.list[self.head] == n:
self.head += 1
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
res = []
mq = MonotonicQueue()
for i in range(0, len(nums)):
if i < k - 1:
mq.push(nums[i])
else:
mq.push(nums[i])
if i - k >= 0:
mq.pop(nums[i - k])
res.append(mq.get_max())
return res