[leetcode ]239. Sliding Window Maximum
2016-04-23 16:45
197 查看
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 =
Therefore, return the max sliding window as
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?
Hint:
How about using a data structure such as deque (double-ended queue)?
The queue size need not be the same as the window’s size.
Remove redundant elements and the queue should store only elements that need to be considered
Solution:
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?
Hint:
How about using a data structure such as deque (double-ended queue)?
The queue size need not be the same as the window’s size.
Remove redundant elements and the queue should store only elements that need to be considered
Solution:
vector<int> maxSlidingWindow(vector<int>& nums, int k) { deque<int> idq; vector<int> result; int i = 0; for (i = 0; i < k - 1; i++) { while (!idq.empty() && (idq.back() < nums[i])) idq.pop_back(); idq.push_back(nums[i]); } for (i = k - 1; i < nums.size(); i++) { while (!idq.empty() && (idq.back() < nums[i])) idq.pop_back(); idq.push_back(nums[i]); result.push_back(idq.front()); if (idq.front() == nums[i - k + 1]) idq.pop_front(); } return result; }
相关文章推荐
- 如何把AChartEngine加载到view视图?
- 40条Android开发优化建议
- 【HDU】 1695 GCD
- 08@设计模式 - (06)复合模式
- 2016年港澳台研究生招生考试报名注意事项
- bzoj3083 遥远的国度
- [转] 中文字体网页开发指南
- 关于对象数组的应用(创建一个学生信息采集系统)
- Solaris相关命令使用
- c语言auto、static、extern、register、volatile存储的理解
- bean的一种使用姿势
- Spark 基础 —— Range
- 【bzoj 2154】Crash的数字表格
- 闪迪打破存储市场格局 加速全闪存存储
- Codeforces 417 C (递推)
- json_encode中文unicode的问题
- VS2013设置护眼背景颜色
- 2016.4.23 GDOI 2016 赛前模拟 总结
- Qt开发环境搭建
- 前端构建工具Gulp使用总结