題目描述:
給定一個數組和滑動窗口的大小,找出所有滑動窗口裏數值的最大值。例如,如果輸入數組
{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]}。
注:本系列均是在牛客網《劍指Offer》在線編程測試通過,並且在VS2015環境下實驗通過;
代碼如下所示:
第一種代碼採用的是容器vector 來存放數組中所有的size大小的子數組個數並放入vector容器中,通過迭代容器中的子數組進行求最大值就好了:
class Solution {
public:
vector<int> maxInWindows(const vector<int>& num, unsigned int size)
{ int max_num = 0;
vector<int> result;
if(num.empty()) return result;
if(size - num.size()) return result;
vector<int> temp;
vector<vector<int>> matrix;
for(int i = 0; i < int(num.size() - size); i++){
for(int j = i;j < i+size;j++){
temp.push_back(num[j]);
}
matrix.push_back(temp);
temp.clear();
}
for(int i = 0;i < matrix.size(); i++){
int temp_ = matrix[i][0];
for(int j = 0; j < matrix[0].size();j++){
temp_ = max(temp_,matrix[i][j]);
}
result.push_back(temp_);
}
return result;
}
};
第二種直接採用在大循環下直接嵌套小循環遍歷就行了時間複雜度爲O(m*n),其中m爲輸入數組大小,n爲窗口大小;
代碼如下所示;
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<int> maxInWindows(const vector<int>& num, unsigned int size)
{
vector<int> result;
if (num.empty()) return result;
if ((int)(num.size() - size) < 0) return result;
for (int i = 0; i < (int)(num.size() - size + 1); i++) {
int max_value = 0;
for (int j = i; j < (int)(i + size); j++) {
if (num[j] > max_value)
max_value = num[j];
}
result.push_back(max_value);
}
return result;
}
};
int main(int argc,char** argv) {
//string ss;
Solution test;
vector<int> test_;
vector<int> temp;
test_.push_back(12);
test_.push_back(13);
test_.push_back(111);
test_.push_back(21);
test_.push_back(45);
test_.push_back(34);
test_.push_back(67);
test_.push_back(78);
test_.push_back(34);
test_.push_back(23);
temp = test.maxInWindows(test_,5);
vector<int>::iterator itr = temp.begin();
while (itr != temp.end()) {
cout << *itr << endl;
itr++;
}
system("pause");
return 0;
}
結果如下
注:
由於這裏面給定的size類型是unsigned int 無符號整型,所以在處理過程中需要進行強制轉換
,還有一點在計算int型和unsigned int型的時候會有一個隱式轉換,也就是int會先轉換成unsigned int型,有時編譯器會將int型轉換成很大的unsigned int,所以這點是需要在實際操作中需要注意的。