Leetcode 661. Image Smoother(Easy)

1.题目

Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.

Example 1:

Input:
[[1,1,1],
 [1,0,1],
 [1,1,1]]
Output:
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]
Explanation:
For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
翻译:给定一个二维整型矩阵M表示图片的灰度,你需要设计一个校平器,使每个元素的灰度变成它和它周围8个灰度的平均值。如果它周围少于8个元素,就有多少用多少。

2.思路

思路1:就是遍历去做。计算每一个点,和他周围的点的平均值,记录到新的矩阵上,最后返回这个新的矩阵。

思路2:有一点优化的想法在里面,比如计算一维数组,计算每个数和其前面n位、其后面n位的数的和;第i位和第i+1位,中间的几位数字是重复的。


3.算法

第二个思路我没有实现,第一个算法

class Solution {
    
    public int[][] res ;
    int row;//行数
    int column;//列数
    
    public int[][] imageSmoother(int[][] M) {
        row = M.length;//矩阵的行数
        column = M[0].length;//矩阵的列数
        res = new int[row][column];
        
        for(int i=0;i<row;i++){
            for(int j=0;j<column;j++){
                res[i][j]=0;
                compute(i,j,M);
            }
        }
        return res; 
    }
    
    private void compute(int m,int n,int[][] source){
        int temp=0;
        int count=0;
        for(int i=m-1;i<=m+1;i++){//行不要越界
            if(i<0||i>=row)continue;
            for(int j=n-1;j<=n+1;j++){//列不要越界
                if(j<0||j>=column)continue;
                temp+=source[i][j];
                count++;
            }
        }
        res[m][n]= (int)temp/count;//求平均值
    }
}

4.总结

最近真的深刻体会到了优化的重要性,要时刻想着优化的事情。

猜你喜欢

转载自blog.csdn.net/crab0314/article/details/80064127