给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
const maxSlidingWindow = (nums, k) => {
const len = nums.length;
if (!len) return [];
const q = [];
for (let i = 0; i < k; i++) {
while (q.length && nums[i] >= nums[q[q.length - 1]]) {
q.pop();
}
q.push(i);
}
const res = [nums[q[0]]];
for (let i = k; i < len; i++) {
while (q.length && nums[i] >= nums[q[q.length - 1]]) {
q.pop();
}
q.push(i);
while (q[0] + k <= i ) q.shift();// 假设nums = [1,-1],k = 1,打个补丁
res.push(nums[q[0]]);
}
return res;
};