牛客网出题出的太不严谨了
当滑动窗口的长度大于数组长度时,到底是返回数组的最大值还是返回空
非要我运行一遍,才能猜透是返回空
class Solution {
public:
vector<int> maxInWindows(const vector<int>& num, unsigned int size)
{
vector<int> result;
int n = num.size();
if (n == 0||size==0||size>n)
return result;
int windows_count = n + 1 - size;
int pre_windows_max = INT_MAX; //保存上一个窗口的最大值
int pre_windows_max_index = -1; //保存上一个窗口的最大值的位置
for (int i = 0; i < windows_count; i++)
{
int cur_max, index;
if (pre_windows_max_index == i - 1)
{
//上一个窗口中的最大值不在这一个窗口内,就要重新计算最大值
cur_max = num[i];
index = i;
for (int j = i+1; j < i + size; j++)
{
if (num[j] >cur_max)
{
cur_max = num[j];
index = j;
}
}
result.push_back(cur_max);
pre_windows_max = cur_max;
pre_windows_max_index = index;
}
else
{
if (pre_windows_max <= num[i + size-1])
{
cur_max = num[i + size-1];
index = i + size-1;
result.push_back(cur_max);
pre_windows_max = cur_max;
pre_windows_max_index = index;
}
else
result.push_back(pre_windows_max);
}
}
return result;
}
};