我开始的方法。。。跟原始人一样 还是太菜
class Solution { public: int FindMax(const vector<int> &a, int start, int end) { int MaxNum = -100000; for (int i = start; i <= end; ++i) { MaxNum = max(MaxNum, a[i]); } return MaxNum; } vector<int> maxInWindows(const vector<int>& num, unsigned int size) { vector<int> re; int in_size = num.size(); if (size <= 0) return re; if (size > 0 && size < in_size) { for (int i = 0; i <= (in_size - size); ++i) { int temp = FindMax(num, i, i + size - 1); re.push_back(temp); } return re; } else if(size==in_size) { int temp=FindMax(num,0,in_size-1); re.push_back(temp); return re; } else return re; } };
更好的方法 利用到队列
class
Solution {
public
:
vector<
int
> maxInWindows(
const
vector<
int
>& num, unsigned
int
size)
{
vector<
int
> res;
deque<
int
> s;
for
(unsigned
int
i=0;i<num.size();++i){
while
(s.size() && num[s.back()]<=num[i])
//从后面依次弹出队列中比当前num值小的元素,同时也能保证队列首元素为当前窗口最大值下标
s.pop_back();
while
(s.size() && i-s.front()+1>size)
//当当前窗口移出队首元素所在的位置,即队首元素坐标对应的num不在窗口中,需要弹出
s.pop_front();
s.push_back(i);
//把每次滑动的num下标加入队列
if
(size&&i+1>=size)
//当滑动窗口首地址i大于等于size时才开始写入窗口最大值
res.push_back(num[s.front()]);
}
return
res;
}
};
来源:https://www.cnblogs.com/159269lzm/p/7275327.html