Set Matrix Zeroes
Problem:
Given a m x n Matrix, if an element was 0, set its entire row and column to 0. Do it on place.
Ideas:
Marking with a tag array
My Code:
Public classSolution { Public voidSetzeroes (int[] matrix) { if(Matrix = =NULL|| Matrix.length = = 0 | | Matrix[0].length = = 0)return; intm =matrix.length; intn = matrix[0].length; int[] row =New int[M]; int[] col =New int[n]; for(inti = 0; I < m; i++) { for(intj = 0; J < N; J + +) { if(Matrix[i][j] = = 0) {Row[i]= 1; COL[J]= 1; } } } for(inti = 0; I < m; i++) { for(intj = 0; J < N; J + +) { if(Row[i] = = 1 | | col[j] = = 1) {Matrix[i][j]= 0; } } } return; }}
View Code
Others code:
Public classSolution {//using O (m+n) is easy and to enable O (1), we have the space within the matrix Public voidSetzeroes (int[] matrix) { if(Matrix = =NULL|| Matrix.length = = 0) return; introws =matrix.length; intcols = matrix[0].length; BooleanEmpty_row0 =false; BooleanEmpty_col0 =false; for(inti = 0; i < cols; i++){ if(Matrix[0][i] = = 0) {empty_row0=true; Break; } } for(inti = 0; i < rows; i++){ if(matrix[i][0] = = 0) {empty_col0=true; Break; } } for(inti = 1; i < rows; i++) { for(intj = 1; j<cols; J + +){ if(Matrix[i][j] = = 0) {matrix[0][J] = 0; matrix[i][0] = 0; } } } for(inti = 1; i<rows; i++) { for(intJ=1; j< cols; J + +) { if(Matrix[0][j] = = 0 | | matrix[i][0] = = 0) Matrix[i][j]= 0; } } if(empty_row0) { for(inti = 0; i < cols; i++) {matrix[0][i] = 0; } } if(empty_col0) { for(inti = 0; i < rows; i++) {matrix[i][0] = 0; } } }}
View Code
The Learning Place:
- The problem itself is characterized by using a tag array to mark which row and column have zero
- My code uses an extra space O (m+n), while others ' code hides the tags in their own people, typically in the possession of people, thus saving space.
- It seems to reduce the complexity of space: 1, increase the time complexity of multiple cycles 2, with their own space for storage, hidden in their own
Set Matrix Zeroes