生成窗口最大值数组

来源:互联网 发布:域名注册检测工具 编辑:程序博客网 时间:2024/06/05 15:26
给出一个整形数组,例如arr = {5,4,3,5,6,7,6},窗口大小为w=3,窗口每次向右移动一位,输出每个窗口中最大值组成的数组。 
[5,4,3,]5,6,7,6 窗口最大值为5 
5,[4,3,5,]6,7,6 窗口最大值为5 
5,4,[3,5,6,]7,6 窗口最大值为6 
5,4,3,[5,6,7,]6 窗口最大值为7 
5,4,3,5,[6,7,6] 窗口最大值为7 

则输出的数组为{5,5,6,7,7};

思路:双端队列,将arr中的元素加入res该队列中,若该队列的队尾元素小于等于要加入的元素,则不断的弹出,直到队尾元素大于该元素或者队列为空。此时将该元素的序号加入队列中。同时当 i-w == 队头的序号,则将队头元素弹出。

////  main.cpp//  生成窗口最大值数组////  Created by zjl on 16/6/2.//  Copyright © 2016年 zjl. All rights reserved.//#include <iostream>#include <deque>#include <vector>using namespace std;vector<int> getMAXWindow(vector<int>vec, int w){    int len = vec.size();    deque<int> q;    vector<int> res;    if(len <= 0 || w < 1 || len < w){        return res;    }    for(int i = 0; i < len; i++){        while(!q.empty() && vec[q.back()] <= vec[i]){            q.pop_back();        }        q.push_back(i);        if(q.front() == i - w)            q.pop_front();        if(i >= w-1)            res.push_back(vec[q.front()]);    }    return res;}int main(int argc, const char * argv[]) {    vector<int> vec = {4,3,5,4,3,3,6,7};    int w = 3; //窗口大小    vector<int> res = getMAXWindow(vec, w);    for(auto i : res)        cout<<i <<" ";    return 0;}


0 0