DS4 滑动窗口的最大值
约 405 字大约 1 分钟
2025-11-04
描述
给定一个长度为 n 的数组 num 和滑动窗口的大小 size ,找出所有滑动窗口里数值的最大值。
例如,如果输入数组{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]}。
窗口大于数组长度或窗口长度为0的时候,返回空。
链接
示例
输入:[2,3,4,2,6,2,5,1],3
返回值:[4,4,6,6,6,5]
输入:[9,10,9,-7,-3,8,2,-6],5
返回值:[10,10,9,8]
输入:[1,2,3,4],5
返回值:[]题解
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param num int整型一维数组
* @param size int整型
* @return int整型一维数组
*/
function maxInWindows(num, size) {
if (size <= 0) return [];
// write code here
let index = 0;
let leng = num.length - size;
let arr = [];
while (index <= leng) {
let item = [];
for (let i = index; i < index + size; i++) {
item.push(num[i]);
}
arr.push(item);
console.log(item);
index++;
}
console.log("arr=", arr);
return arr.map((e) => {
return e.reduce((pre, cur) => {
if (cur > pre) return cur;
return pre;
}, e[0]);
});
}
module.exports = {
maxInWindows: maxInWindows,
};
// console.log(maxInWindows([2, 3, 4, 2, 6, 2, 5, 1], 3));