题目链接:https://leetcode-cn.com/problems/sliding-window-maximum/
1 class Solution { 2 public: 3 vector<int> maxSlidingWindow(vector<int>& nums, int k) { 4 vector< int > ans; 5 deque< int > DQ; 6 7 if(nums.empty()) return ans; 8 for(int i = 0; i <= k - 1; ++i) { 9 while(!DQ.empty() && nums[i] > nums[DQ.back()]) DQ.pop_back(); 10 DQ.push_back(i); 11 } 12 13 ans.push_back(nums[DQ.front()]); 14 for(int i = k; i < (int)nums.size(); ++i) { 15 if(i - k == DQ.front()) DQ.pop_front(); 16 while(!DQ.empty() && nums[i] > nums[DQ.back()]) DQ.pop_back(); 17 DQ.push_back(i); 18 ans.push_back(nums[DQ.front()]); 19 } 20 21 return ans; 22 } 23 };
原文:https://www.cnblogs.com/zaq19970105/p/11342735.html