zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    C++指针
    Linux Ubuntu常用终端命令
    java-JDBC-Oracle数据库连接
    HDU 1890 区间反转
    Hdu-3487 Splay树,删除,添加,Lazy延迟标记操作
    UVa 10088
    UVa10025-The ? 1 ? 2 ? ... ? n = k problem
    UVa10023手动开大数平方算法
    UVa 10007
    点的双联通+二分图的判定(poj2942)
  • 原文地址:https://www.cnblogs.com/DreamKill/p/12609768.html
Copyright © 2011-2022 走看看