Skip to content

Commit 2b41ad2

Browse files
authored
Update 0239-滑动窗口最大值.py
1 parent 68f9661 commit 2b41ad2

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed

0239.滑动窗口最大值/0239-滑动窗口最大值.py

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,33 @@
1+
1.利用双端队列记录当前滑动窗口的元素索引
2+
2.队列最左侧元素记录滑动窗口中最大元素的索引
3+
3.遍历数组
4+
如果队列最左侧索引已不在滑动窗口范围内弹出队列最左侧索引
5+
通过循环确保队列的最左侧索引所对应元素值最大
6+
新元素入队
7+
从第一个滑动窗口的末尾索引开始将最大值存储到结果res中
8+
9+
class Solution:
10+
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
11+
res = []
12+
# queue = collections.deque() #如果不用deque,用list也行
13+
queue=[]
14+
for i, num in enumerate(nums):
15+
if queue and queue[0] == i - k:
16+
# queue.popleft()
17+
queue.pop(0)
18+
while queue and nums[queue[-1]] < num: #比 nums[i] 小的都不要,因为只要窗口的最大值
19+
queue.pop()
20+
queue.append(i)
21+
if i >= k - 1:
22+
res.append(nums[queue[0]])
23+
return res
24+
25+
作者郁郁雨
26+
链接https://leetcode.cn/problems/sliding-window-maximum/solutions/626777/239-hua-dong-chuang-kou-zui-da-zhi-li-yo-2jqr/
27+
来源力扣LeetCode
28+
著作权归作者所有商业转载请联系作者获得授权非商业转载请注明出处
29+
30+
#和上面相同,变量名称不同
131
class Solution(object):
232
def maxSlidingWindow(self, nums, k):
333
"""
@@ -11,13 +41,13 @@ def maxSlidingWindow(self, nums, k):
1141
window = []
1242
res = []
1343
for i in range(len(nums)):
14-
if window and window[0] <= i - k: #当前window头应该被弹出
44+
if window and window[0] <= i - k: #当前window头应该被弹出
1545
window.pop(0)
1646

17-
while window and nums[window[-1]] < nums[i]: #比 nums[i] 小的都不要,因为只要窗口的最大值
47+
while window and nums[window[-1]] < nums[i]: #比 nums[i] 小的都不要,因为只要窗口的最大值
1848
window.pop()
1949

2050
window.append(i)
2151
if i >= k - 1:
2252
res.append(nums[window[0]])
23-
return res
53+
return res

0 commit comments

Comments
 (0)