加载中...
661-图片平滑器(Image Smoother)
发表于:2021-12-03 | 分类: 简单
字数统计: 902 | 阅读时长: 4分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/image-smoother

英文原文

An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).

Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it.

 

Example 1:

Input: img = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[0,0,0],[0,0,0],[0,0,0]]
Explanation:
For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the points (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

Example 2:

Input: img = [[100,200,100],[200,50,200],[100,200,100]]
Output: [[137,141,137],[141,138,141],[137,141,137]]
Explanation:
For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137
For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141
For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138

 

Constraints:

  • m == img.length
  • n == img[i].length
  • 1 <= m, n <= 200
  • 0 <= img[i][j] <= 255

中文题目

包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) ,平均灰度的计算是周围的8个单元和它本身的值求平均,如果周围的单元格不足八个,则尽可能多的利用它们。

示例 1:

输入:
[[1,1,1],
 [1,0,1],
 [1,1,1]]
输出:
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]
解释:
对于点 (0,0), (0,2), (2,0), (2,2): 平均(3/4) = 平均(0.75) = 0
对于点 (0,1), (1,0), (1,2), (2,1): 平均(5/6) = 平均(0.83333333) = 0
对于点 (1,1): 平均(8/9) = 平均(0.88888889) = 0

注意:

  1. 给定矩阵中的整数范围为 [0, 255]。
  2. 矩阵的长和宽的范围均为 [1, 150]。

通过代码

官方题解

方法 1:遍历矩阵

想法和算法

对于矩阵中的每一个单元格,找所有 9 个包括它自身在内的紧邻的格子。

然后,我们要将所有邻居的和保存在 ans[r][c] 中,同时记录邻居的数目 count。最终的答案就是和除以邻居数目。

[]
class Solution(object): def imageSmoother(self, M): R, C = len(M), len(M[0]) ans = [[0] * C for _ in M] for r in xrange(R): for c in xrange(C): count = 0 for nr in (r-1, r, r+1): for nc in (c-1, c, c+1): if 0 <= nr < R and 0 <= nc < C: ans[r][c] += M[nr][nc] count += 1 ans[r][c] /= count return ans
[]
class Solution { public int[][] imageSmoother(int[][] M) { int R = M.length, C = M[0].length; int[][] ans = new int[R][C]; for (int r = 0; r < R; ++r) for (int c = 0; c < C; ++c) { int count = 0; for (int nr = r-1; nr <= r+1; ++nr) for (int nc = c-1; nc <= c+1; ++nc) { if (0 <= nr && nr < R && 0 <= nc && nc < C) { ans[r][c] += M[nr][nc]; count++; } } ans[r][c] /= count; } return ans; } }

复杂度分析

  • 时间复杂度:$O(N)$,其中 $N$ 是图片中像素的数目。我们需要将每个像素都遍历一遍。

  • 空间复杂度:$O(N)$,我们答案的大小。

统计信息

通过次数 提交次数 AC比率
17407 30947 56.2%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言
上一篇:
662-二叉树最大宽度(Maximum Width of Binary Tree)
下一篇:
664-奇怪的打印机(Strange Printer)
本文目录
本文目录