73. 矩阵置零
给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。
示例 1:

输入:matrix = [[1,1,1],[1,0,1],[1,1,1]] 输出:[[1,0,1],[0,0,0],[1,0,1]]
示例 2:

输入:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] 输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]
方法:标记数组 时间O(m*n) 空间O(m+n)
思路:我们首先遍历该数组一次,如果某个元素为 0,那么就将该元素所在的行和列所对应标记数组的位置置为 true。最后我们再次遍历该数组,用标记数组更新原数组即可。
// row={i=0, i=1, i=2};
// col={j=0; j=1; j=2; j=3}
1 class Solution { 2 public void setZeroes(int[][] matrix) { 3 int m = matrix.length; 4 int n = matrix[0].length; 5 // row={i=0, i=1, i=2}; 6 // col={j=0; j=1; j=2; j=3} 7 boolean[] row = new boolean[m]; 8 boolean[] col = new boolean[n]; 9 10 for(int i=0; i<m; i++){ 11 for(int j=0; j<n; j++){ 12 if(matrix[i][j]==0){ 13 row[i] = true; 14 col[j] = true; 15 } 16 } 17 } 18 for(int i=0; i<m; i++){ 19 for(int j=0; j<n; j++){ 20 if(row[i] || col[j]) matrix[i][j]=0; 21 } 22 } 23 24 } 25 }