这题用单调队列是最合适的,一开始没想到用的是类似于这种思路的自设逻辑的暴力法
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
int left = 0;
int right = left + k - 1;
int maxNum = *max_element(&nums[left],&nums[right]+1);
vector<int> ans;
ans.push_back(maxNum);
while (right < (int)nums.size()-1)
{
if (nums[right + 1] > maxNum)
{
maxNum = nums[right + 1];
ans.push_back(maxNum);
++left;
++right;
}
else if (nums[left] == maxNum && nums[left+1]!=maxNum)
{
++left;
++right;
maxNum = *max_element(&nums[left], &nums[right] + 1);
ans.push_back(maxNum);
}
else
{
ans.push_back(maxNum);
++left;
++right;
}
}
return ans;
}
};