661. 图片平滑器题解
题目来源:661. 图片平滑器
2022.03.24 每日一题
LeetCode 题解持续更新中Github仓库地址 CSDN博客地址
今天的题目就很简单了,按照题意进行模拟就好,注意模拟的时候边界的范围,不要越界
class Solution {
public:
// 创建方向数组,进行各个方向上的统计
vector<vector<int>> dirs = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 0}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
// 创建两个变量统计数组的长和宽
int m, n;
vector<vector<int>> imageSmoother(vector<vector<int>> &img) {
// 分别将长和宽进行赋值
m = img.size();
n = img[0].size();
// 创建一个等大的数组
vector<vector<int>> res(m, vector<int>(n));
// 遍历各个值,进行统计
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
res[i][j] = cnt(img, i, j);
return res;
}
int cnt(vector<vector<int>> &img, int i, int j) {
// 统计数值的个数
int count = 0;
// 统计数值的加和
// 题目中 最大值是 255 ,因此使用 int 是安全的
int sum = 0;
for (vector<int> &dir: dirs) {
int x = i + dir[0], y = j + dir[1];
if (x < 0 || y < 0 || x >= m || y >= n) continue;
count++;
sum += img[x][y];
}
return sum / count;
}
};
class Solution {
// 创建方向数组,进行各个方向上的统计
public int[][] dirs = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 0}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
// 创建两个变量统计数组的长和宽
int m, n;
public int[][] imageSmoother(int[][] img) {
// 分别将长和宽进行赋值
m = img.length;
n = img[0].length;
// 创建一个等大的数组
int[][] res = new int[m][n];
// 遍历各个值,进行统计
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
res[i][j] = cnt(img, i, j);
return res;
}
public int cnt(int[][] img, int i, int j) {
// 统计数值的个数
int count = 0;
// 统计数值的加和
// 题目中 最大值是 255 ,因此使用 int 是安全的
int sum = 0;
for (int[] dir : dirs) {
int x = i + dir[0], y = j + dir[1];
if (x < 0 || y < 0 || x >= m || y >= n) continue;
count++;
sum += img[x][y];
}
return sum / count;
}
}
- 时间复杂度 O ( 9 m n ) O(9mn) O(9mn)
- 空间复杂度 O ( 1 ) O(1) O(1)