题解 | #滑动窗口的最大值#
滑动窗口的最大值
https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param num int整型一维数组 * @param size int整型 * @return int整型一维数组 */ function maxInWindows(num, size) { // write code here if (size > num.length || size == 0) return []; let firstArr = num.slice(0, size); max = findmax(firstArr); let res = []; res.push(max); //裁切数组,左闭右开 let heap = num.slice(0, size); for (i = size; i < num.length; i++) { //删除堆里面第一个元素 let temp = heap.shift(); heap.push(num[i]); //当前的值和上一次的最大值比较,如果比上一次最大还大就返回当前值,如果小,就继续寻找最大 if (num[i] >= res[res.length-1]) { maxRes = num[i]; } else { maxRes = findmax(heap); } res.push(maxRes); } return res; } function findmax(arr) { let max = arr[0]; for (let i = 0; i < arr.length; i++) { max = Math.max(max, arr[i]); } return max; } module.exports = { maxInWindows: maxInWindows, };