标签:
Use additional O(m+n) space, simple improvement. Two array, one is of size row, to store the status of each row, whether there is a 0 element in the row. Similarly, the other array of size col, storing the status of each column that whether there is 0 element in the column. Then traverse the arrays, if the current element is true, which represents that there are at least one 0 element in the row(column). Then set all the elements in the row(column) to be zero.
Code:
public class Solution { public void setZeroes(int[][] matrix) { int row = matrix.length; int col = matrix[0].length; boolean[] isZeroColumn = new boolean[col]; boolean[] isZeroRow = new boolean[row]; for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ if(matrix[i][j]==0) { isZeroRow[i] = true; isZeroColumn[j] = true; } } } for(int i = 0; i < row; i++){ if(isZeroRow[i]){ for(int j = 0; j < col; j++) matrix[i][j] = 0; } } for(int i = 0; i < col; i++){ if(isZeroColumn[i]){ for(int j = 0; j < row; j++) matrix[j][i] = 0; } } } }
Jan 20 - Set Matrix Zeros; Array;
标签:
原文地址:http://www.cnblogs.com/5683yue/p/5147102.html