
Problem
Solution
Analysis
Python implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class : def imageSmoother(self, M): """ :type M: List[List[int]] :rtype: List[List[int]] """ m, n = len(M), len(M[0]) result = [[0]*n for _ in range(m)] for r in range(m): for c in range(n): count = 0 for i in range(r-1, r+2): for j in range(c-1, c+2): if 0<=i<m and 0<=j<n: result[r][c] += M[i][j] count +=1 result[r][c] = result[r][c]//count return result
|
Java implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class { public int[][] imageSmoother(int[][] M) { int m = M.length; int n = M[0].length; int[][] result = new int[m][n]; for(int r = 0; r < m; r++){ for(int c = 0; c < n; c++){ int count = 0; for(int i = r-1; i < r+2; i++){ for(int j = c-1; j < c+2; j++){ if(i>=0 && i<m && j>=0 && j<n){ result[r][c] += M[i][j]; count++; } } } result[r][c] /= count; } } return result; } }
|
Time complexity
O(mn).
Space complexity
O(mn).
Link
661. Image Smoother
(中文版) 算法笔记: 力扣#661 图片平滑器
近期评论