剑指0ffer59.滑动窗口的最大值
给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
示例:
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[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
提示:
你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
1.暴力解。
2.双端队列模拟滑动窗口。使队头元素保持为滑动窗口的最大值,并根据滑动窗口的大小k删除队头元素。根据当前位置nums[i]值删除队尾元素。
//暴力解, 二重循环
class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector<int> ans; if(!nums.size()) return ans; for(int i=0; i<nums.size()-k+1; i++){ int max=INT_MIN; for(int j=i; j<i+k; j++){ if(nums[j]>max){ max = nums[j]; } } ans.push_back(max); } return ans; } };
//双端队列模拟滑动窗口
class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector<int> ans; if(nums.empty()) return ans; deque<int> q; for(int i=0; i<k; i++){
//队尾元素只能通过判别当前元素删除。且不能取等号。 while(!q.empty()&&q.back()<nums[i]) q.pop_back(); q.push_back(nums[i]); } ans.push_back(q.front()); for(int i=k; i<nums.size(); i++){
//队头元素出队,周期为k。 if(q.front()==nums[i-k]) q.pop_front(); // while(q.front()<=nums[i]&&q.size()>0) // q.pop_front(); while(!q.empty()&&q.back()<nums[i]) q.pop_back(); q.push_back(nums[i]); ans.push_back(q.front()); } return ans; } };