100378. 设计相邻元素求和服务
给你一个 n x n
的二维数组 grid
,它包含范围 [0, n2 - 1]
内的不重复元素。
实现 neighborSum
类:
neighborSum(int [][]grid)
初始化对象。int adjacentSum(int value)
返回在 grid
中与 value
相邻的元素之和,相邻指的是与 value
在上、左、右或下的元素。int diagonalSum(int value)
返回在 grid
中与 value
对角线相邻的元素之和,对角线相邻指的是与 value
在左上、右上、左下或右下的元素。
示例 1:
输入:
["neighborSum", "adjacentSum", "adjacentSum", "diagonalSum", "diagonalSum"]
[[[[0, 1, 2], [3, 4, 5], [6, 7, 8]]], [1], [4], [4], [8]]
输出: [null, 6, 16, 16, 4]
解释:
示例 2:
输入:
["neighborSum", "adjacentSum", "diagonalSum"]
[[[[1, 2, 0, 3], [4, 7, 15, 6], [8, 9, 10, 11], [12, 13, 14, 5]]], [15], [9]]
输出: [null, 23, 45]
解释:
提示:
3 <= n == grid.length == grid[0].length <= 10
0 <= grid[i][j] <= n2 - 1
grid[i][j]
值均不重复。adjacentSum
和 diagonalSum
中的 value
均在范围 [0, n2 - 1]
内。adjacentSum
和 diagonalSum
总共 2 * n2
次。原站题解
rust 解法, 执行用时: 16 ms, 内存消耗: 2.4 MB, 提交时间: 2024-11-09 00:07:58
use std::collections::HashMap; const dirs: [ &[(i32, i32)]; 2] = [ &[(-1, 0), (1, 0), (0, -1), (0, 1)], &[(-1, -1), (-1, 1), (1, -1), (1, 1)], ]; struct NeighborSum { grid: Vec<Vec<i32>>, pos: HashMap<i32, (usize, usize)>, } /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl NeighborSum { fn new(grid: Vec<Vec<i32>>) -> Self { let mut pos = HashMap::new(); for (i, row) in grid.iter().enumerate() { for (j, &val) in row.iter().enumerate() { pos.insert(val, (i, j)); } } NeighborSum { grid, pos } } fn adjacent_sum(&self, value: i32) -> i32 { self.get_sum(value, 0) } fn diagonal_sum(&self, value: i32) -> i32 { self.get_sum(value, 1) } fn get_sum(&self, value: i32, idx: usize) -> i32 { if let Some(&(x, y)) = self.pos.get(&value) { let mut sum = 0; for &(dx, dy) in dirs[idx] { let nx = x as i32 + dx; let ny = y as i32 + dy; if nx >= 0 && (nx as usize) < self.grid.len() && ny >= 0 && (ny as usize) < self.grid[0].len() { sum += self.grid[nx as usize][ny as usize]; } } sum } else { 0 } } } /** * Your neighborSum object will be instantiated and called as such: * let obj = neighborSum::new(grid); * let ret_1: i32 = obj.adjacent_sum(value); * let ret_2: i32 = obj.diagonal_sum(value); */
javascript 解法, 执行用时: 28 ms, 内存消耗: 60.1 MB, 提交时间: 2024-11-09 00:06:41
var NeighborSum = function(grid) { this.grid = grid; this.pos = {}; for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[0].length; j++) { this.pos[grid[i][j]] = [i, j]; } } }; const dirs = [ [[-1, 0], [1, 0], [0, -1], [0, 1]], [[-1, -1], [-1, 1], [1, -1], [1, 1]] ]; NeighborSum.prototype.adjacentSum = function(value) { return this.getSum(value, 0); }; NeighborSum.prototype.diagonalSum = function(value) { return this.getSum(value, 1); }; NeighborSum.prototype.getSum = function(value, idx) { const [x, y] = this.pos[value]; let sum = 0; for (const [dx, dy] of dirs[idx]) { const nx = x + dx; const ny = y + dy; if (nx >= 0 && nx < this.grid.length && ny >= 0 && ny < this.grid[0].length) { sum += this.grid[nx][ny]; } } return sum; } /** * Your neighborSum object will be instantiated and called as such: * var obj = new neighborSum(grid) * var param_1 = obj.adjacentSum(value) * var param_2 = obj.diagonalSum(value) */
cpp 解法, 执行用时: 137 ms, 内存消耗: 68.3 MB, 提交时间: 2024-08-06 15:58:32
class neighborSum { static constexpr int dirs[8][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}}; vector<array<int, 2>> s; public: neighborSum(vector<vector<int>>& grid) { int n = grid.size(); s.resize(n * n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int v = grid[i][j]; for (int k = 0; k < 8; k++) { int x = i + dirs[k][0], y = j + dirs[k][1]; if (0 <= x && x < n && 0 <= y && y < n) { s[v][k / 4] += grid[x][y]; } } } } } int adjacentSum(int value) { return s[value][0]; } int diagonalSum(int value) { return s[value][1]; } }; /** * Your neighborSum object will be instantiated and called as such: * neighborSum* obj = new neighborSum(grid); * int param_1 = obj->adjacentSum(value); * int param_2 = obj->diagonalSum(value); */
java 解法, 执行用时: 16 ms, 内存消耗: 44.3 MB, 提交时间: 2024-08-06 15:58:12
class neighborSum { private static final int[][] DIRS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}}; private final int[][] s; public neighborSum(int[][] grid) { int n = grid.length; s = new int[n * n][2]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int v = grid[i][j]; for (int k = 0; k < 8; k++) { int x = i + DIRS[k][0]; int y = j + DIRS[k][1]; if (0 <= x && x < n && 0 <= y && y < n) { s[v][k / 4] += grid[x][y]; } } } } } public int adjacentSum(int value) { return s[value][0]; } public int diagonalSum(int value) { return s[value][1]; } } /** * Your neighborSum object will be instantiated and called as such: * neighborSum obj = new neighborSum(grid); * int param_1 = obj.adjacentSum(value); * int param_2 = obj.diagonalSum(value); */
golang 解法, 执行用时: 57 ms, 内存消耗: 7.3 MB, 提交时间: 2024-08-06 15:57:56
var dirs = []struct{ x, y int }{{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}} type neighborSum [][2]int func Constructor(grid [][]int) neighborSum { n := len(grid) s := make(neighborSum, n*n) for i, row := range grid { for j, v := range row { for k, d := range dirs { x, y := i+d.x, j+d.y if 0 <= x && x < n && 0 <= y && y < n { s[v][k/4] += grid[x][y] } } } } return s } func (s neighborSum) AdjacentSum(value int) int { return s[value][0] } func (s neighborSum) DiagonalSum(value int) int { return s[value][1] } /** * Your neighborSum object will be instantiated and called as such: * obj := Constructor(grid); * param_1 := obj.AdjacentSum(value); * param_2 := obj.DiagonalSum(value); */
python3 解法, 执行用时: 127 ms, 内存消耗: 16.8 MB, 提交时间: 2024-08-06 15:57:34
# 偏移向量,前四:上下左右,后四:右上、左上、左下、右下 DIRS = ((-1, 0), (1, 0), (0, -1), (0, 1), (1, 1), (-1, 1), (-1, -1), (1, -1)) class neighborSum: def __init__(self, grid: List[List[int]]): n = len(grid) s = [[0, 0] for _ in range(n * n)] for i, row in enumerate(grid): for j, v in enumerate(row): for k, (dx, dy) in enumerate(DIRS): x, y = i + dx, j + dy if 0 <= x < n and 0 <= y < n: s[v][k // 4] += grid[x][y] self.s = s def adjacentSum(self, value: int) -> int: return self.s[value][0] def diagonalSum(self, value: int) -> int: return self.s[value][1] # Your neighborSum object will be instantiated and called as such: # obj = neighborSum(grid) # param_1 = obj.adjacentSum(value) # param_2 = obj.diagonalSum(value)