2373.矩阵中的局部最大值
链接:2373.矩阵中的局部最大值
难度:Easy
标签:数组、矩阵
简介:找出 grid 中每个 3 x 3 矩阵中的最大值。
题解 1 - cpp
- 编辑时间:2023-03-01
- 执行用时:12ms
- 内存消耗:10.8MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
vector<vector<int>> largestLocal(vector<vector<int>>& grid) {
int n = grid.size();
vector<vector<int>> res(n - 2, vector<int>(n - 2, 0));
for (int i = 1; i < n - 1; i++) {
for (int j = 1; j < n - 1; j++) {
for (int row = i - 1; row <= i + 1; row++) {
for (int col = j - 1; col <= j + 1; col++) {
res[i - 1][j - 1] = max(res[i - 1][j - 1], grid[row][col]);
}
}
}
}
return res;
}
};
题解 2 - python
- 编辑时间:2023-03-01
- 执行用时:36ms
- 内存消耗:15.5MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:
n = len(grid)
res = [[0] * (n-2) for _ in range(n-2)]
for i in range(1, n-1):
for j in range(1, n-1):
res[i-1][j-1] = max(
grid[row][col]
for row in range(i-1, i+2)
for col in range(j-1, j+2)
)
return res
题解 3 - rust
- 编辑时间:2023-03-01
- 执行用时:4ms
- 内存消耗:2.2MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
pub fn largest_local(grid: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let n = grid.len();
let mut res = vec![vec![0; n - 2]; n - 2];
for i in 1..(n - 1) {
for j in 1..(n - 1) {
for row in (i - 1)..=(i + 1) {
for col in (j - 1)..=(j + 1) {
res[i - 1][j - 1] = res[i - 1][j - 1].max(grid[row][col]);
}
}
}
}
res
}
}