滑动窗口最大值

1.给定一个任意数组,和一个大小为w的窗口,该窗口从左到右依次滑动,得到窗口的每个状态下的最大值

 1 // maxWindow.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include <deque>
 7 #include <vector>
 8 #include <iterator>
 9 
10 using namespace std;
11 
12 void getMaxWindow(vector<int> &arr,int w)
13 {
14     vector<int> result;
15     int len = arr.size();
16     if(len == 0 || w < 1 || len < w)
17         return ;
18 
19     deque<int> qmax;
20     for(int i = 0; i < len;i++)
21     {    //1.在双端队列中始终维护一组下标,下标对应的数由大到小的排序
22         while(!qmax.empty() && arr[qmax.back()] < arr[i])
23             qmax.pop_back();
24         qmax.push_back(i);
25         //2.窗口刚好滑过去。往前弹出
26         if(qmax.front() == i - w)
27             qmax.pop_front();
28         //3.从w-1位置开始每一步都收集相应的数
29         if(i >= w-1)
30             result.push_back(arr[qmax.front()]);
31     }
32     vector<int>::iterator ite = result.begin();
33     for(;ite != result.end();ite++)
34         cout<<*ite<<" ";
35     cout<<endl;
36 }
37 
38 int _tmain(int argc, _TCHAR* argv[])
39 {
40     vector<int> arr;
41     arr.push_back(4);
42     arr.push_back(3);
43     arr.push_back(5);
44     arr.push_back(4);
45     arr.push_back(3);
46     arr.push_back(3);
47     arr.push_back(6);
48     arr.push_back(7);
49     int w = 3;
50     getMaxWindow(arr,w);
51     system("pause");
52     return 0;
53 }
View Code
原文地址:https://www.cnblogs.com/lp3318/p/5767264.html