leetcode 算法题661 (简单166) 图片平滑器
- 题目介绍
包含整数的二维矩阵 M 表示一个图片的灰度。
你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) ,
平均灰度的计算是周围的8个单元和它本身的值求平均,
如果周围的单元格不足八个,
则尽可能多的利用它们。
- 示例
输入:
[[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
- 注意
- 给定矩阵中的整数范围为 [0, 255]。
- 矩阵的长和宽的范围均为 [1, 150]。
- 解法一
/**
* @param {number[][]} M
* @return {number[][]}
*/
var imageSmoother = function(M) {
let temp = [], i = 0;
while(i < M.length) {
temp[i] = [];
let j = 0;
while(j < M[i].length) {
temp[i][j] = averageSmoother(M, i, j++);
}
i++;
}
return temp;
};
const averageSmoother = (M, i, j) => {
let count = sum = 0, left = right = j, top = bottom = i;
if(i > 0) {
top = i - 1;
}
if(i < M.length - 1) {
bottom = i + 1;
}
if(j > 0) {
left = j - 1;
}
if(j < M[i].length - 1) {
right = j + 1;
}
while(top <= bottom) {
let k = left;
while(k <= right) {
sum += M[top][k++];
count++;
}
top++;
}
return Math.floor(sum / count);
}
执行用时 : 724 ms, 在所有 JavaScript 提交中击败了 6.38%的用户
内存消耗 : 90.8 MB, 在所有 JavaScript 提交中击败了 6.45%的用户
- 解法二
/**
* @param {number[][]} M
* @return {number[][]}
*/
var imageSmoother = function(M) {
let strategys = [
[-1, -1], [-1, 0], [-1, 1],
[0, -1], [0, 0], [0, 1],
[1, -1], [1, 0], [1, 1]
];
let x = 0, row = M.length;
while(x < row) {
let y = 0, col = M[x].length;
while(y < col) {
let z = 0;
while(z < strategys.length) {
let point = [x + strategys[z][0], y + strategys[z][1]];
if(isPoint(point, row, col)) {
M[x][y] += (1 << 20);
M[x][y] += ((M[point[0]][point[1]] & 255) << 8);
}
z++;
}
y++;
}
x++;
}
x = 0;
while(x < row) {
let y = 0, col = M[x].length;
while(y < col) {
let temp = M[x][y];
let count = temp >> 20;
let sum = (temp >> 8) - (count << 12);
M[x][y++] = Math.floor(sum / count);
}
x++;
}
return M;
};
let isPoint = (point, row, col) => {
return point[0] >= 0 && point[1] >= 0 && point[0] < row && point[1] < col;
}
执行用时 : 152 ms, 在所有 JavaScript 提交中击败了 100.00%的用户
内存消耗 : 42.8 MB, 在所有 JavaScript 提交中击败了 29.03%的用户