给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
双端队列:既可以从头部进出也可以从尾部进出。
使用双端队列头部存储最大值的下标,使用尾部存储候选最大值的下标。
在存入下标前,首先判断该下标对应的值是否大于队列尾部的候选值,如果大于就删除尾部,即将该值变为了候选最大值。
如果队列头部的数字已经滑出了窗口,则滑出数字也需从队列头部删除掉。
时间复杂度:O(N)
空间复杂度:O(N)
function maxInWindows(num, size)
{
// write code here
var res = [];
if(size == 0) return res;
var begin, queue = [];
for(var i = 0; i < num.length; i++) {
begin = i - size + 1;
if(queue.length == 0) {
queue.push(i);
} else if(begin > queue[0]) {
queue.shift()
}
while((queue.length != 0) && (num[queue[queue.length -1]]) <= num[i]){
queue.pop();
}
queue.push(i);
if(begin >= 0) {
res.push(num[queue[0]])
}
}
return res
}