# 【LeetCode】239. Sliding Window Maximum 解题报告（Python&C++）

900 篇文章 155 订阅
1033 篇文章 56 订阅

id： fuxuemingzhu

## 题目描述

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]

Explanation:

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
1 [3  -1  -3] 5  3  6  7       3
1  3 [-1  -3  5] 3  6  7       5
1  3  -1 [-3  5  3] 6  7       5
1  3  -1  -3 [5  3  6] 7       6
1  3  -1  -3  5 [3  6  7]      7


Note:

• You may assume k is always valid, 1 ≤ k ≤ input array’s size for non-empty array.

• Could you solve it in linear time?

## 解题方法

### 单调递减队列

python代码如下：

class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
que = collections.deque() # [[i, num]]
res = []
for i, num in enumerate(nums):
if que and i - que[0][0] >= k:
que.popleft()
while que and que[-1][1] <= num:
que.pop()
que.append([i, num])
if i >= k - 1:
res.append(que[0][1])
return res


### MultiSet

class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res;
multiset<int> st;
for (int i = 0; i < nums.size(); ++i) {
if (st.size() >= k) st.erase(st.find(nums[i - k]));
st.insert(nums[i]);
if (i >= k - 1)
res.push_back(*st.rbegin());
}
return res;
}
};


## 日期

2019 年 9 月 14 日 —— 假期的生活就是不规律

• 0
点赞
• 0
收藏
• 打赏
• 0
评论
09-27 419
08-16 28
02-25 74
12-14 1419

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。