当前位置: 代码迷 >> 综合 >> Set Matrix Zeroes - Leetcode
  详细解决方案

Set Matrix Zeroes - Leetcode

热度:18   发布时间:2023-12-17 05:33:20.0

方法1 (m+n)

public class Solution {public void setZeroes(int[][] matrix) {boolean[] row = new boolean[matrix.length];boolean[] col = new boolean[matrix[0].length];for(int i=0; i<matrix.length; i++)for(int j=0; j<matrix[0].length; j++){if(matrix[i][j]==0){row[i]=true;col[j]=true;}}for(int i=0; i<row.length; i++){if(row[i]==true){for(int j=0; j<matrix[0].length; j++)matrix[i][j]=0;}}for(int j=0; j<col.length; j++){if(col[j]==true){for(int i=0; i<matrix.length; i++)matrix[i][j]=0;}}}
}


方法2 (n)

public class Solution {public void setZeroes(int[][] matrix) {boolean row_zero = false, col_zero = false;for(int i=0; i<matrix.length; i++){if(matrix[i][0] == 0)col_zero = true;}for(int j=0; j<matrix[0].length; j++){if(matrix[0][j] == 0)row_zero = true;}for(int i=1; i<matrix.length; i++)for(int j=1; j<matrix[0].length; j++){if(matrix[i][j]==0){matrix[i][0]=0; matrix[0][j]=0;}}for(int i=1; i<matrix.length; i++)for(int j=1; j<matrix[0].length; j++){if(matrix[i][0] ==0 || matrix[0][j]==0){matrix[i][j] = 0;}}if(row_zero){for(int j=0; j<matrix[0].length; j++)matrix[0][j]=0;}if(col_zero){for(int i=0; i<matrix.length; i++)matrix[i][0]=0;}}
}


分析:题目要求空间消耗最小。方法1:声明2个数组,一个代码行,一个代表列。然后遍历2维数组,如果有为0的就将行和列分别在两个数组中记录。最后,跟两个数组的记录,修改2维数组。 空间复杂度O(M+N)

方法2:重复用2维数组的第一行,第一列。

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.