0
点赞
收藏
分享

微信扫一扫

LeetCode 661. 图片平滑器

小禹说财 2022-03-24 阅读 61
leetcode

题目链接:

力扣icon-default.png?t=M276https://leetcode-cn.com/problems/image-smoother/

 【分析】对于i,j处的格子,计算[i - 1, i + 1],[j - 1, j + 1]范围内的和以及元素个数即可,需要注意处理边界。

class Solution {
    public int[][] imageSmoother(int[][] img) {

        int m = img.length;
        int n = img[0].length;
        int[][] ans = new int[m][n];
        int i, j, x1, y1, x2, y2, p, q, sum, num;
        for(i = 0; i < m; i++){
            for(j = 0; j < n; j++){
                x1 = i - 1; if(x1 < 0) x1 = 0;
                y1 = j - 1; if(y1 < 0) y1 = 0;
                x2 = i + 1; if(x2 >= m) x2 = m - 1;
                y2 = j + 1; if(y2 >= n) y2 = n - 1;
                sum = 0; num = 0;
                for(p = x1; p <= x2; p++){
                    for(q = y1; q <= y2; q++){
                        sum += img[p][q]; num++;
                    }
                }
                ans[i][j] = sum / num;
            }
        }
        return ans;
    }
}

 【方法二】前缀和,占个位置,后面补充。

 

举报

相关推荐

0 条评论