劍指offer——滑動視窗的最大值
阿新 • • 發佈:2018-12-09
概述
題目描述
給定一個數組和滑動視窗的大小,找出所有滑動窗口裡數值的最大值。例如,如果輸入陣列{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]}。
C++ AC程式碼
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> maxInWindows(const vector<int>& num, unsigned int size){
vector<int> ans;
if(num.empty() || size < 1 || num.size() < size){
return ans;
}
for (int i = 0 ; i <= num.size()-size ; i++){
int max = num[i];
for(int j = i+1 ; j < i+size ; j++){
if(num[j] > max){
max = num[j];
}
}
ans.push_back(max);
}
return ans;
}
};