leetcode 算法题661 (简单166) 图片平滑器

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
  • 注意
  1. 给定矩阵中的整数范围为 [0, 255]。
  2. 矩阵的长和宽的范围均为 [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%的用户

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值