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;
        }
    };



  • 相关阅读:
    DataGrid和GridView鼠标移动上面背景变色
    Javascript页面跳转常用代码(测试通过)
    设为首页,加入收藏夹
    Javascript实现金额千分位自动分位
    对用户输入内容进行字数提示功能
    Javascript网页刷新方法集锦(测试通过)
    asp.net 上传图片并作处理 水印 缩略图(测试OK)
    ASP.NET常用函数(参考用)
    Javascript弹出对话框 确定取消转到不同页面
    silverligth +wcf 下载文件
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5285154.html
Copyright © 2011-2022 走看看