239. 滑动窗口最大值

给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 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

板子题,维护个单调栈就行了,居然还是个hard

 

pair<int,int>skt[100004];
class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
         vector<int>ans;
         int siz = nums.size();
         int top(0),right(1);
         for(int i=0;i<k;++i){
             while(top&&skt[top].second<nums[i])--top;
             skt[++top]=make_pair(i,nums[i]);
         }
      /*   [1,-1]
          1*/
         ans.push_back(skt[right].second);
         for(int i=k;i<siz;++i){
             while(right<=top&&top&&skt[top].second<nums[i])--top;
             skt[++top]=make_pair(i,nums[i]);
             while(right<=top&&skt[top].first-skt[right].first+1>k)++right;
           //  skt[++top]=make_pair(i,nums[i]);
             ans.push_back(skt[right].second);
         }
         return ans;
    }
};

 

posted @ 2020-04-01 00:04  Xzavieru  阅读(94)  评论(0编辑  收藏  举报