矩阵置零-中等

难度:中等

题目描述:
给定一个  m x n  的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用**原地算法

**示例:**

输入: [
  [1, 1, 1],
  [1, 0, 1],
  [1, 1, 1],
];
输出: [
  [1, 0, 1],
  [0, 0, 0],
  [1, 0, 1],
];
1
2
3
4
5
6
7
8
9
10


解题思路: ```javascript var setZeroes = function(matrix) { var rows={} var column={} for(var i=0;i==0){ rows[i]=false column[j]=false } } for(var i=0;i==false)||(column[j]==false)) matrix[i][j]=0 } }; ```


常数空间复杂度

var setZeroes = function (matrix) {
  let rowLen = matrix.length;
  let colLen = matrix[0].length;
  for (let i = 0; i < rowLen; i++) {
    for (let j = 0; j < colLen; j++) {
      if (matrix[i][j] == 0) {
        for (let rowI = 0; rowI < rowLen; rowI++) {
          if (matrix[rowI][j] != 0) {
            matrix[rowI][j] = true;
          }
        }
        for (let colI = 0; colI < colLen; colI++) {
          if (matrix[i][colI] != 0) {
            matrix[i][colI] = true;
          }
        }
      }
    }
  }
  for (let i = 0; i < rowLen; i++) {
    for (let j = 0; j < colLen; j++) {
      if (typeof matrix[i][j] == "boolean") {
        matrix[i][j] = 0;
      }
    }
  }
  return matrix;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28


巧设-0

var setZeroes = function (matrix) {
  let rowLen = matrix.length;
  let colLen = matrix[0].length;
  for (let i = 0; i < rowLen; i++) {
    for (let j = 0; j < colLen; j++) {
      if (matrix[i][j] == 0 && 1 / matrix[i][j] > 0) {
        for (let rowI = 0; rowI < rowLen; rowI++) {
          if (matrix[rowI][j] != 0) {
            matrix[rowI][j] = -0;
          }
        }
        for (let colI = 0; colI < colLen; colI++) {
          if (matrix[i][colI] != 0) {
            matrix[i][colI] = -0;
          }
        }
      }
    }
  }
  return matrix;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
最后更新时间: 6/8/2020, 8:24:16 PM