前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 239. Sliding Window Maximum

Leetcode 239. Sliding Window Maximum

作者头像
triplebee
发布2018-01-12 14:31:08
4910
发布2018-01-12 14:31:08
举报

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.

For example, Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

代码语言:javascript
复制
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

Therefore, return the max sliding window as [3,3,5,5,6,7].

Note:  You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.

Follow up: Could you solve it in linear time?

用一个滑窗在数组上滑动,求滑动到每个位置时,滑窗内数字的最大值,线性时间内完成。

使用双端队列完成,队列记录数组中的下标,维护多个单调递减区间。

当当前下标和队列首的元素相差超过k-1时,说明滑窗超过了既定大小,需要把前一个元素扔掉。

因为要维护单调递增,所以每次加入一个新的下标时,需要将新加入的数和队列尾的数字比较,扔掉比新加入的数小的数,因为它们不可能是滑窗内的最大值。

当下标大于等于k-1的时候,说明要开始记录滑窗的最大值了。

代码语言:javascript
复制
class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        vector<int> res;
        deque<int> q;
        for(int i = 0; i < nums.size(); i++)
        {
            if(!q.empty() && i - q.front() >= k) q.pop_front();
            while(!q.empty() && nums[q.back()] <= nums[i]) q.pop_back();
            q.push_back(i);
            if(i >= k - 1) res.push_back(nums[q.front()]);
        }
        return res;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-04-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档