每日两题 T25

时间:2022-07-22
本文章向大家介绍每日两题 T25,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

算法

LeetCode T542. 01 矩阵[1]

描述

给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。

两个相邻元素间的距离为 1 。

示例1:

输入
0 0 0
0 1 0
0 0 0

输出
0 0 0
0 1 0
0 0 0

示例2:

输入
0 0 0
0 1 0
1 1 1

输出
0 0 0
0 1 0
1 2 1

注意:

1.给定矩阵的元素个数不超过 10000。2.给定矩阵中至少有一个元素是 0。3.矩阵中的元素只在四个方向上相邻: 上、下、左、右。

分析

典型的动态规划问题

代码

/**
 * @param {number[][]} matrix
 * @return {number[][]}
 */
var updateMatrix = function (matrix) {
  // dp optimise
  if (matrix.length == 0) {
    return [];
  }
  let m = matrix.length, n = matrix[0].length;
  // left-top to right-bottom
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (matrix[i][j] != 0) {
        matrix[i][j] = m + n;
        if (i > 0) {
          matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j]);
        }
        if (j > 0) {
          matrix[i][j] = Math.min(matrix[i][j - 1] + 1, matrix[i][j]);
        }
      }
    }
  }
  // right-bottom to left-top
  for (let i = m - 1; i >= 0; i--) {
    for (let j = n - 1; j >= 0; j--) {
      // distance
      if (matrix[i][j] != 0) {
        if (j < n - 1) {
          matrix[i][j] = Math.min(matrix[i][j], matrix[i][j + 1] + 1);
        }
        if (i < matrix.length - 1) {
          matrix[i][j] = Math.min(matrix[i][j], matrix[i + 1][j] + 1);
        }
      }
    }
  }
  return matrix;
};

JavaScript

请手写 bindapply

实现bind,要注意几个点

1.生成新函数的prototype应该是指向当前作用域的原型2.还要保证新创建的函数原型及函数对象的私有原型正确

Function.prototype.bind2 = function (context) {

    if (typeof this !== "function") {
      throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
    }

    const self = this;
    const args = Array.prototype.slice.call(arguments, 1);
    const fNOP = function () {};

    const fbound = function () {
        self.apply(this instanceof self ? this : context, args.concat(Array.prototype.slice.call(arguments)));
    }

    fNOP.prototype = this.prototype;
    fbound.prototype = new fNOP();

    return fbound;

}

实现apply,不借助bind或call实现

Function.prototype.apply2 = function (context, arr) {
    var context = Object(context) || window;
    context.fn = this;

    var result;
    if (!arr) {
        result = context.fn();
    }
    else {
        var args = [];
        for (var i = 0, len = arr.length; i < len; i++) {
            args.push('arr[' + i + ']');
        }
        result = eval('context.fn(' + args + ')')
    }

    delete context.fn
    return result;
}

References

[1] 542. 01 矩阵: https://leetcode-cn.com/problems/01-matrix/