• 滑动窗口的最大值


    题目:给定一个数组和滑动窗口的大小,请找到所有滑动窗口里的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别是{4,4,6,6,6,5},如图所示:

     1 #include<iostream>
     2 #include<vector>
     3 #include<deque>
     4 using namespace std;
     5 
     6 vector<int> maxInWindows(const vector<int>& num,unsigned int size)
     7 {
     8  vector<int> MaxInWindows;
     9  if(num.size()>size&&size>=1)
    10  {
    11   deque<int> index;
    12   for(unsigned int i=0;i<size;++i)
    13   {
    14    while(!index.empty()&&num[i]>=num[index.back()])
    15      index.pop_back();
    16    index.push_back(i);
    17    }
    18   for(i=size;i<num.size();++i)
    19   {
    20     MaxInWindows.push_back(num[index.front()]);
    21     while(!index.empty()&&num[i]>=num[index.back()])
    22     index.pop_back();
    23     if(!index.empty()&&index.front()<(int)(i-size))
    24         index.pop_front();
    25     index.push_back(i);
    26   }
    27  MaxInWindows.push_back(num[index.front()]);
    28  }
    29 return MaxInWindows;
    30 }
    31 
    32 void print(vector<int> result)
    33 {
    34     vector<int>::iterator ite;
    35     for(ite=result.begin();ite!=result.end();++ite)
    36         cout<<*ite<<" ";
    37         cout<<endl;
    38          result.clear();
    39 }
    40 
    41 void main()
    42 {
    43     int ia[10]={1,2,3,4,5,6,7,8,9,10};
    44     vector<int> ib(ia,ia+10);
    45     print(maxInWindows(ib,3));
    46 }

     方法2:

     1 #include<iostream>
     2 #include<vector>
     3 #include<deque>
     4 using namespace std;
     5 
     6 
     7 int searchmax(const vector<int>&num,unsigned int size)
     8 {
     9      int max=num[0];
    10     for(int i=1;i<size;i++)
    11     {
    12         if(num[i]>max)
    13             max=num[i];
    14     }
    15     return max;
    16 }
    17 
    18 vector<int> maxInWindows(vector<int>& num,unsigned int size)
    19 {
    20  vector<int> MaxInWindows;
    21  int length=num.size();
    22  for(int i=0;i<length-size+1;i++)
    23  {
    24   MaxInWindows.push_back(searchmax(num,size));
    25       num.erase(num.begin());
    26  }
    27 return MaxInWindows;
    28 }
    29 
    30 
    31     
    32 
    33 void print(vector<int> result)
    34 {
    35     vector<int>::iterator ite;
    36     for(ite=result.begin();ite!=result.end();++ite)
    37         cout<<*ite<<" ";
    38         cout<<endl;
    39          result.clear();
    40 }
    41 
    42 void main()
    43 {
    44     int ia[10]={1,2,3,4,5,6,7,8,9,10};
    45     vector<int> ib(ia,ia+10);
    46     print(maxInWindows(ib,3));
    47     print(ib);
    48 }
  • 相关阅读:
    Object-c NSArray
    内存管理池
    Objuct-c 对象的初始化 存起器 属性 self和super 内存管理
    继承什么的
    Object C 多态性
    Objectvie
    (重点) 协议
    分类
    一张图了解Python
    转载 MySql常用查询语句(23种)
  • 原文地址:https://www.cnblogs.com/wxdjss/p/5479189.html
Copyright © 2020-2023  润新知