Title Description
Given an array and the size of the sliding window, sliding window to find the maximum value among all values. For example, if the input array size and {2,3,4,2,6,2,5,1} 3 sliding window, then the presence of a total of six sliding window, their maximum values is {4,4,6, 6,6,5}; it has the following six array {2,3,4,2,6,2,5,1} for the sliding window: {[2,3,4], 2,6,2,5 , 1}, {2, [3,4,2], 6,2,5,1}, {2,3, [4,2,6], 2, 5}, {2,3,4 , [2,6,2], 5,1}, {2,3,4,2, [6,2,5], 1}, {2,3,4,2,6, [2,5, 1]}.
Solution:
1, define two vector arrays, array size elements stored at each sliding window, the maximum value stored MaxNum
2, (), array.end () array.begin () Get the maximum max_element by *
. 3, by vector :: iterator idx = array.begin () ; array.erase (idx); delete array element head
class Solution {
public:
vector<int> maxInWindows(const vector<int>& num, unsigned int size)
{
vector<int> maxnum;//保存最大值
vector<int> array;//保存每次窗口滑动后的数组
unsigned int length = num.size();//原num数组的长度
unsigned int k = 0;//记录遍历num的位置
if (size>length || size<1)
return maxnum;
while (k < size-1)
array.push_back(num[k++]);
for (int i=0; i<length-size+1; i++)
{
array.push_back(num[k++]);
maxnum.push_back(*max_element(array.begin(), array.end()));//保存当前滑动窗口内的最大值
vector<int>::iterator idx = array.begin();
array.erase(idx);//删除array中头部元素
}
return maxnum;
}
};