chencl1986/Blog

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

Opened this issue · 0 comments

原题链接:
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
}