Given an m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
A simple improvement is to make use of two arrays of lengthm and n , respectively, indicating which rows and columns need to be set to 0. In this way, the space complexity is reduced to O(m+n) .
A simple improvement is to make use of two arrays of lengthm and n , respectively, indicating which rows and columns need to be set to 0. In this way, the space complexity is reduced to O(m+n) .
Code from http://www.programcreek.com/2012/12/leetcode-set-matrix-zeroes-java/
A simple improvement is to make use of two arrays of length
A simple improvement is to make use of two arrays of length
Code from http://www.programcreek.com/2012/12/leetcode-set-matrix-zeroes-java/
public void setZeroes(int[][] matrix) { boolean firstRowZero = false; boolean firstColumnZero = false; //set first row and column zero or not for(int i=0; i<matrix.length; i++){ if(matrix[i][0] == 0){ firstColumnZero = true; break; } } for(int i=0; i<matrix[0].length; i++){ if(matrix[0][i] == 0){ firstRowZero = true; break; } } //mark zeros on first row and column 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; } } } //use mark to set elements 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; } } } //set first column and row if(firstColumnZero){ for(int i=0; i<matrix.length; i++) matrix[i][0] = 0; } if(firstRowZero){ for(int i=0; i<matrix[0].length; i++) matrix[0][i] = 0; } }Read full article from LeetCode - Set Matrix Zeroes | Darren's Blog
No comments:
Post a Comment