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

LeetCode题解:2373. 矩阵中的局部最大值,遍历,详细注释 #484

Open
chencl1986 opened this issue Oct 24, 2024 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:
https://leetcode.cn/problems/largest-local-values-in-a-matrix/

解题思路:

  1. 原题需要生成矩阵 maxLocalmaxLocal[i][j] 等于 grid 中以 i + 1 行和 j + 1 列为中心的 3 x 3 矩阵中的 最大值
  2. 这句话的意思等同于 maxLocal[i][j] 等于 grid 中以 i 行和 j 列为左上角的 3 x 3 矩阵中的 最大值
/**
 * @param {number[][]} grid
 * @return {number[][]}
 */
var largestLocal = function (grid) {
  const n = grid.length // 缓存矩阵的长宽
  // 创建存储结果的数组
  let result = Array.from({ length: n - 2 }, () => new Array(n - 2).fill(0))

  // 创建大小为(n - 2) x (n - 2) 的整数矩阵
  for (let i = 0; i < n - 2; i++) {
    for (let j = 0; j < n - 2; j++) {
      let max = -Infinity // 缓存最大值

      // 搜索以i和j为左上角,长宽为3的矩阵中的最大值
      for (let k = 0; k < 3; k++) {
        for (let l = 0; l < 3; l++) {
          max = Math.max(max, grid[i + k][j + l])
        }
      }

      // 将最大值存储到结果矩阵相应位置
      result[i][j] = 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