LeetCode题解:239. 滑动窗口最大值,双循环暴力,JavaScript,详细注释

605 阅读1分钟

原题链接:leetcode-cn.com/problems/sl…

解题思路:

参考了官方题解的方法一。

  1. 遍历每个滑块的起始点。
  2. 从起始点开始,遍历后续滑块元素。
  3. 对比滑块中元素的最大值,并存入结果。
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var maxSlidingWindow = function (nums, k) {
  let result = [];

  // 遍历滑块的起始点
  for (let i = 0; i < nums.length - k + 1; i++) {
    let max = nums[i];

    // 按照滑块宽度,查找后续元素,并对比最大值
    for (let j = i + 1; j < i + k; j++) {
      max = Math.max(max, nums[j]);
    }

    // 比对完滑块所有元素之后,将最大值存入result
    result.push(max);
  }

  return result;
};