滑动窗口专题 - leetcode239. Sliding Window Maximum - hard

1. 题目描述

You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.

Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]

Explanation:
Window position Max


[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7

Example 2:

Input: nums = [1], k = 1
Output: [1]

Example 3:

Input: nums = [1,-1], k = 1
Output: [1,-1]

Example 4:

Input: nums = [9,11], k = 2
Output: [11]

Example 5:

Input: nums = [4,-2], k = 2
Output: [4]

Constraints:

1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length

2. 题解

思路:
开辟一个队列,并保证队首始终是当前滑动窗口的最大值,遍历数组,比较当前数组元素和队尾元素的值,如果比队尾元素大就将队尾出队。
细节:
1、队列中应该存储元素的下标,因为元素是可以重复的,下标是唯一的;
2、若队首的下标恰好是上一个窗口的第一个元素的下标时,出队首。

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var maxSlidingWindow = function(nums, k) {
    if(nums.length === 1){
        return nums;
    }
    const max = [];
    const queue = [];
    for(let i = 0; i < nums.length; i++){
        //当前队首是上个窗口第一个元素时出队
        if(queue.length > 0 && queue[0] === i-k){
           queue.shift();
        }
        //队列不空且队列末尾的值小于当前的i元素
        while(queue.length > 0 && nums[queue[queue.length-1]] < nums[i]){
              queue.pop();
        }
        //当前i元素的下标入队
        queue.push(i);
        //从下标k-1可以有窗口的最大值
        if(i >= k-1){
           max.push(nums[queue[0]]);
        }
    }
    return max;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值