zoukankan      html  css  js  c++  java
  • 239. Sliding Window Maximum

    Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

    For example,
    Given nums = 
    [1,3,-1,-3,5,3,6,7], and k = 3.

     

    Window position                Max
    ---------------               -----
    [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

    Therefore, return the max sliding window as [3,3,5,5,6,7].

    Note: 
    You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.

    Follow up:
    Could you solve it in linear time?

    Hint:

    1. How about using a data structure such as deque (double-ended queue)?
    2. The queue size need not be the same as the window’s size.
    3. Remove redundant elements and the queue should store only elements that need to be considered.

    思路:按照提示,利用deque储存数组的下标,保持deque的头部始终存储当前窗口最大的数的下标。每次循环,剔除deque中比nums[i]小的数。将窗口右边界数的下标加入deque中,同时剔除deque头部越界的序号。当遍历的数已经达到窗口的大小时,此时deque头部的数的下标就是当前窗口的最大的那个数的下标,将这个数加入最终返回的那个数组中。

    class Solution {
    public:
        vector<int> maxSlidingWindow(vector<int>& nums, int k) {
            vector<int> ret;
            deque<int>q;
            for(int i=0;i<nums.size();i++){
                //只在deque中保留最大的数
                while(!q.empty()&&nums[i]>=nums[q.back()])
                    q.pop_back();
                //每次后移窗口,加入i
                q.push_back(i);
                //将越界的front剔除
                if(q.front()<=i-k)
                    q.pop_front();
                //当达到窗口大小的时候,将deque中的最大值加入ret数组
                if(i>=k-1)
                    ret.push_back(nums[q.front()]);
            }
            return ret;
        }
    };



  • 相关阅读:
    Android防止手动添加的本地库文件被NDK工具清理掉
    将驱动编译进Linux内核
    cocos2d-x入门学习笔记——Hello world分析
    linux内核开发入门学习
    makefile工程管理
    GDB程序调试工具
    ios学习笔记_20140308
    Mac Os学习笔记-下载黑屏
    时间过得好快
    做一个关于预防接种的app
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5285154.html
Copyright © 2011-2022 走看看