跳到主要内容

3242.设计相邻元素求和服务

链接:3242.设计相邻元素求和服务
难度:Easy
标签:设计、数组、哈希表、矩阵、模拟
简介:给你一个 n x n 的二维数组 grid,它包含范围 [0, n2 - 1] 内的不重复元素。实现 neighborSum 类。

题解 1 - undefined

  • 编辑时间:2024-11-09
  • 执行用时:28ms
  • 内存消耗:16.89MB
  • 编程语言:undefined
  • 解法介绍:遍历
dirs1 = [(0, 1), (1, 0), (0, -1), (-1, 0)]
dirs2 = [(1, 1), (1, -1), (-1, 1), (-1, -1)]
class NeighborSum:
def __init__(self, grid: List[List[int]]):
self.grid = grid
self.n = len(grid)
self.m = len(grid[0])
self.map = {grid[i][j]: (i, j) for i in range(self.n) for j in range(self.m)}
def get(self, value: int, dirs: List[int]) -> int:
i, j = self.map[value]
res = 0
for dir in dirs:
ni = i + dir[0]
nj = j + dir[1]
if 0 <= ni < self.n and 0 <= nj < self.m:
res += self.grid[ni][nj]
return res
def adjacentSum(self, value: int) -> int:
return self.get(value, dirs1)
def diagonalSum(self, value: int) -> int:
return self.get(value, dirs2)