Skip to content

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

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

Open
chencl1986 opened this issue Sep 5, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:https://leetcode-cn.com/problems/sliding-window-maximum/

解题思路:

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

  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;
};
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