LeetCode 661. 图片平滑器题解

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值