此题研究目标所在的窗口大小固定,窗口的边界并不一定是窗口内的最大值,所以可以通过一个双端队列的数据结构来维护
class Solution {
public:vector<int> maxSlidingWindow(vector<int>& nums, int k) {deque<int> dq;vector<int> ret;int n = nums.size();int l = 0, r= 0;while(r < n){if(r - l == k){if(dq.front() == nums[l]){dq.pop_front();}++l;}while(!dq.empty() && nums[r] > dq.back()){dq.pop_back();}dq.push_back(nums[r]);if(r - l == k - 1){ret.push_back(dq.front());}r++;}return ret;}
};