题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
// 57.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <deque>
#include <vector>
using namespace::std;
class Solution {
public:
vector<int> maxInWindows(const vector<int>& num, unsigned int size) {
vector<int> retVec;
if (num.empty() || size < 1 || num.size() < size) return retVec;
deque<int> que;
int max = num[0];
for (int i = 0; i < size; i++) {
que.push_back(num[i]);
if (num[i] > max) max = num[i];
}
retVec.push_back(max);
for (int i = size; i < num.size(); i++) {
que.pop_front();
que.push_back(num[i]);
int max = que[0];
for (deque<int>::iterator it = que.begin(); it != que.end(); ++it) {
if (max < *it) max = *it;
}
retVec.push_back(max);
}
return retVec;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int arr[] = { 2, 3, 4, 2, 6, 2, 5, 1 };
vector<int> test(arr, arr + 8);
Solution s;
vector<int> result = s.maxInWindows(test, 3);
return 0;
}