- 滑动窗口最大值
给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
返回 滑动窗口中的最大值
自己写的答案,但是时间复杂度超了
var maxSlidingWindow = function(nums, k) {
const log = []
for(let i=0;i<=nums.length-k;i++){
const topk = nums.slice(i,i+k)
const max = Math.max(...topk)
log.push(max)
}
return log
};
正确答案,双端队列
function maxSlidingWindow(nums, k) {
if (!nums || nums.length === 0) return [];
if (k === 1) return nums;
const deq = []; // 使用数组模拟双端队列
const result = [];
for (let i = 0; i < nums.length; i++) {
// 移除不在当前窗口内的索引
if (deq.length > 0 && deq[0] < i - k + 1) {
deq.shift();
}
// 移除队列中所有比当前元素小的索引
while (deq.length > 0 && nums[deq[deq.length - 1]] < nums[i]) {
deq.pop();
}
// 将当前元素的索引加入队列
deq.push(i);
// 当窗口形成后,开始记录结果
if (i >= k - 1) {
result.push(nums[deq[0]]);
}
}
return result;
}
// 示例测试
const nums = [1, 3, -1, -3, 5, 3, 6, 7];
const k = 3;
console.log(maxSlidingWindow(nums, k)); // 输出: [3, 3, 5, 5, 6, 7]```