-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path239.Sliding-Window-Maximum.py
52 lines (41 loc) · 1.15 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
41
42
43
44
45
46
47
48
49
50
51
52
# https://leetcode.com/problems/sliding-window-maximum/
#
# algorithms
# Hard (37.06%)
# Total Accepted: 137,871
# Total Submissions: 372,038
# beats 79.21% of python submissions
from collections import deque
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
queue = deque()
for i in xrange(k):
length = len(queue)
while length > 0:
if nums[i] >= nums[queue[-1]]:
queue.pop()
length -= 1
else:
break
queue.append(i)
res = []
for i in xrange(k, len(nums)):
res += nums[queue[0]],
if i - queue[0] + 1 > k:
queue.popleft()
length = len(queue)
while length > 0:
if nums[i] >= nums[queue[-1]]:
queue.pop()
length -= 1
else:
break
queue.append(i)
if len(queue) > 0:
res += nums[queue[0]],
return res