Leetcode 239. Sliding Window Maximum
来源:互联网 发布:淘宝店铺装修全屏海报 编辑:程序博客网 时间:2024/05/24 06:42
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.
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的时候,说明要开始记录滑窗的最大值了。
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; }};
1 0
- [leetcode] 239.Sliding Window Maximum
- [LeetCode]239.Sliding Window Maximum
- leetcode 239. Sliding Window Maximum
- LeetCode 239. Sliding Window Maximum
- [leetcode] 239. Sliding Window Maximum
- leetcode.239. Sliding Window Maximum
- LeetCode-239.Sliding Window Maximum
- leetcode 239. Sliding Window Maximum
- Leetcode-239. Sliding Window Maximum
- Leetcode 239. Sliding Window Maximum
- leetcode 239.Sliding Window Maximum
- [LeetCode]239. Sliding Window Maximum
- Leetcode 239. Sliding Window Maximum
- [LeetCode]239. Sliding Window Maximum
- Leetcode 239. Sliding Window Maximum
- Leetcode 239. Sliding Window Maximum
- [leetcode]239. Sliding Window Maximum
- LeetCode 239. Sliding Window Maximum
- linux 编译指定库、头文件的路径问题
- JAVA集合Set使用
- Android Studio2.3打包项目后,安装时提示无签名的解决方法
- 使用xhprof进行线上PHP性能追踪及分析
- 文件的上传
- Leetcode 239. Sliding Window Maximum
- 母函数
- Struts2使用OGNI
- JAVA期终考试总结
- Uncaught TypeError: Cannot set property ' ' of null 错误解决
- nfs网络共享文件设置
- 虚拟机挂在共享文档
- VC++对话框学习总结
- BZOJ 1228: [SDOI2009]E&D 博弈,SG函数,组合游戏