Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

239. 滑动窗口最大值 #69

Open
webVueBlog opened this issue Sep 5, 2022 · 0 comments
Open

239. 滑动窗口最大值 #69

webVueBlog opened this issue Sep 5, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

239. 滑动窗口最大值

Description

Difficulty: 困难

Related Topics: 队列, 数组, 滑动窗口, 单调队列, 堆(优先队列)

给你一个整数数组 nums,有一个大小为 k的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。

返回 滑动窗口中的最大值

示例 1:

输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
输出:[3,3,5,5,6,7]
解释:
滑动窗口的位置                最大值
---------------               -----
[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

示例 2:

输入:nums = [1], k = 1
输出:[1]

提示:

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

Solution

Language: JavaScript

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
//  单调队列有两个难点:
// 第一是实现窗口内的单调性,当进入滑动窗口的元素大于等于队尾的元素时 不断从队尾出队,直到进入滑动窗口的元素小于队尾的元素,才可以入队,以保证单调递减的性质;
// 第二是实现滑动性,即一个过期机制,出了窗口就要从单调队列中剔除;
// 当队头元素已经在滑动窗口外了,移除队头元素
var maxSlidingWindow = function(nums, k) {
    const q = [];
    const ans = [];
    for (let i = 0; i < nums.length; i++) {
        // 当单调队列不为空,且当前数大于单调队列队尾的数,则需要弹出队尾的数(因其不可能为最大值,无价值) 单调性维护
        while (q.length && nums[i] >= nums[q[q.length - 1]]) {
            q.pop();
        }
        q.push(i);
        // 滑动性过期维护(去除队首已确认报文), i-k即恰好滑出窗口元素的下标
        while (q[0] <= i - k) {
            q.shift();
        }
        // 当i大于等于k - 1时,将此时队首元素加入res数组
        // 此处判断主要是为了解决前k个元素只能进入一个最大值
        // 将此时队首元素加入res数组
        if (i >= k - 1) ans.push(nums[q[0]])
    }
    return ans;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant