leetcode-Sliding Window Maximum
来源:互联网 发布:山西省软件开发企业 编辑:程序博客网 时间:2024/05/21 18:40
Total Accepted: 14811 Total Submissions: 62176 Difficulty: Hard
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 thek 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?
class Solution {public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { if(nums.empty()||k<=0) return vector<int>(); deque<int> qmax; for(int i=0;i<k;++i){ while(!qmax.empty()&&nums[qmax.back()]<=nums[i]) qmax.pop_back(); qmax.push_back(i); } vector<int> res; res.push_back(nums[qmax.front()]); int len=nums.size(); int left=1; for(int right=k;right<len;++left,++right){ while(!qmax.empty()&&nums[qmax.back()]<=nums[right]) qmax.pop_back(); qmax.push_back(right); if(qmax.front()<left) qmax.pop_front(); res.push_back(nums[qmax.front()]); } return res; }};
0 0
- leetcode Sliding Window Maximum
- [LeetCode]Sliding Window Maximum
- leetcode - Sliding Window Maximum
- LeetCode - Sliding Window Maximum
- Leetcode: Sliding Window Maximum
- [LeetCode]Sliding Window Maximum
- LeetCode Sliding Window Maximum
- [LeetCode]Sliding Window Maximum
- [leetcode] Sliding Window Maximum
- LeetCode Sliding Window Maximum
- LeetCode || Sliding Window Maximum
- [LeetCode]Sliding Window Maximum
- leetcode: Sliding Window Maximum
- *LeetCode-Sliding Window Maximum
- [leetcode]Sliding Window Maximum
- Leetcode -- Sliding Window Maximum
- leetcode-Sliding Window Maximum
- [LeetCode] Sliding Window Maximum
- git 本地分支与远程分支
- HDU 3435 A new Graph Game (KM)
- 深入解析单例模式
- SDK初步认识
- HighCharts 曲线
- leetcode-Sliding Window Maximum
- Inversion 逆序对
- Android-常用第三方库proguard-rules配置
- python3 与 python2的 区别比较
- Qt在线安装
- 功能框架的补充
- 第4讲项目2--------第四小节 求圆柱体的表面积
- 关于内存对齐
- hive 建表例子