title : Matrix 0
Difficulty : Easy
topic content :
Given a m x n Matrix, if an element was 0, set its entire row and column to 0. Do it in-place.
translation :
Given an m x n matrix, if an element is 0, its entire row and column is set to 0.
Requirement: Place 0.
Example 1:
Input: [[1,1,1], [1,0,1], [1,1,1]]output: [[1,0,1], [0,0,0], [1,0,1]]
Example 2:
Input: [[0,1,2,0], [3,4,5,2], [1,3,1,5]]output: [[0,0,0,0], [0,4,5,0], [0,3,1,0]]
my idea : Because the requirement is in place, so cannot create a new matrix, and then meet 0 will be placed in the row all 0
So it's all over again, and all 0 of the rows are labeled with list<integer[]>, the number No. 0 is row, and the 1th is the column.
Then loop this list, call the 0 method respectively.
My Code :
1 Public voidSetzeroes (int[] matrix) {2 if(Matrix.length = = 0 | | matrix[0].length = = 0)3 return;4list<integer[]> list =NewArraylist<integer[]>();5 for(inti = 0; i < matrix.length; i++) {6 for(intj = 0; J < Matrix[0].length; J + +) {7 if(Matrix[i][j] = = 0) {8List.add (Newinteger[]{i,j});9 }Ten } One } A for(integer[] x:list) { -Setzero (Matrix, x[0], x[1]); - } the } - - Public voidSetzero (int[] Matrix,intIintj) { - for(intn = 0; n < matrix.length; n++) { +MATRIX[N][J] = 0; - } + for(intm = 0; M < matrix[0].length; m++) { AMatrix[i][m] = 0; at } -}
my complexity : O (m*n) + O ((m+n) *x) x is the number of 0 in the matrix
problems in the programming process :
1. No
(integer[in code] can be replaced with int[]
Answer code :
1 Public voidSetzeroes (int[] matrix) {2 if(Matrix.length = = 0 | | matrix[0].length = = 0)3 return;4 Booleanrow =false, col =false;5 for(inti = 0; i < matrix.length; i++) {6 for(intj = 0; J < Matrix[0].length; J + +) {7 if(Matrix[i][j] = = 0) {8 if(i = = 0) row =true;9 if(j = = 0) col =true;TenMatrix[i][0] = 0; OneMATRIX[0][J] = 0; A } - } - } the for(inti = 1; i < matrix.length; i++) {//Note that this should be starting from 1, because the "0,0" if the 0 is also judged by the No. 0 column (the flag column) all set to 0, then the entire matrix will be 0 - if(matrix[i][0] = = 0) { - for(intj = 0; J < Matrix[0].length; J + +) { -MATRIX[I][J] = 0; + } - } + } A for(intj = 1; J < Matrix[0].length; J + +) {// at if(Matrix[0][j] = = 0) { - for(inti = 0; i < matrix.length; i++) { -MATRIX[I][J] = 0; - } - } - } in if(row) { - for(intj = 0; J < Matrix[0].length; J + +) { toMATRIX[0][J] = 0; + } - } the if(col) { * for(inti = 0; i < matrix.length; i++) { $Matrix[i][0] = 0;Panax Notoginseng } - } the}
complexity of the answer : O (m*n)
The answer : using rows No. 0 and No. 0 as the "flag bit" and setting two Boolean variables to record whether the "flag bit" needs to be set 0, this method compared to my method in the last 0 to avoid the repetition of 0 of the action, the original matrix of more than 0, Only O (m*n) secondary 0 is required
Leetcode [73] (Java): Set Matrix Zeroes (matrix 0)