原题链接
思路:暴力解法和双端队列。
暴力解法:窗口每次移动都去找当前窗口内的最大值。
双端队列:存储元素的的下标,队列中下标的对应元素是从大到小的顺讯,并按时判断当前队列中的最大值是否还在窗口内。
暴力解法:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int maxInt(int* nums, int left, int numsSize){
int max = -100000000;
for(int i = 0; i < numsSize; i++){
if(nums[left + i] > max) max = nums[left + i];
}
return max;
}
int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize){
if(numsSize ==0 ){
*returnSize = 0;
return nums;
}
if(k == 1){
*returnSize = numsSize;
return nums;
}
*returnSize = numsSize - k + 1;
int* arr = (int*)malloc(sizeof(int)*(numsSize - k + 1));
for(int i = 0; i < numsSize - k + 1; i++){
arr[i] = maxInt(nums, i, k);
}
return arr;
}
双端队列:
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res
deque<int> tem;
for(int i=0; i<nums.size(); ++i)
{
while(!tem.empty() && nums[i]>nums[tem.back()]) tem.pop_back();
if(!tem.empty() && tem.front()<i-k+1) tem.pop_front();
tem.push_back(i);
if(i>=k-1) res.push_back(nums[tem.front()]);
}
return res;
}
};