题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。
1 class Solution { 2 public: 3 vector<int> maxInWindows(const vector<int>& num, unsigned int size) 4 { 5 vector<int> vet; 6 int len = num.size(); 7 if(len==0||size==0||size>len) 8 return vet; 9 if(size==len) 10 { 11 vector<int> vet1 = num; 12 sort(vet1.begin(), vet1.end()); 13 vet.push_back(vet1.back()); 14 return vet; 15 } 16 17 18 int max =INT_MIN; 19 for (int i = 0; i <= len-size; i++) 20 { 21 for (int j = i; j < i + size; j++) 22 { 23 if (max < num[j]) 24 max = num[j]; 25 26 } 27 vet.push_back(max); 28 max = INT_MIN; 29 } 30 return vet; 31 } 32 };