Two solutions list as below: one is using separate row and column arrays respectively to mark which row and column to set zeros. After a full matrix scan, we have these two arrays set, and then loop them separately and set zeros. Be careful of zero row and column.
Another one is to use the zero row and column as the mark arrays. But before jumping into the full scan, be scan zero row and column first to set the zeroRow and zeroColumn flags respectively. Then full scan from index 1, and loop through zero row and zero column respectively, set zeros from index 1 too. After all if zeroRow flag or/and zeroColumn flag is set, change the zero row/column to zeros.
public class Solution {
public void setZeroes(int[][] matrix) {
if(matrix ==null || matrix.length == 0){
return;
}
boolean zeroColumn = false;
boolean zeroRow = false;
for(int m = 0; m < matrix.length; m++){
if(matrix[m][0] == 0){
zeroColumn = true;
}
}
for(int n = 0; n < matrix[0].length; n++){
if(matrix[0][n] == 0){
zeroRow = true;
}
}
for(int m = 1; m < matrix.length; m++){
for(int n = 1; n < matrix[0].length; n++){
if(matrix[m][n] == 0){
matrix[m][0] = 0;
matrix[0][n] = 0;
}
}
}
for(int m = 1; m < matrix.length; m++){
if(matrix[m][0] == 0){
for(int n = 1; n < matrix[0].length; n++){
matrix[m][n] = 0;
}
}
}
for(int n = 1; n < matrix[0].length; n++){
if(matrix[0][n] == 0){
for(int m = 1; m < matrix.length; m++){
matrix[m][n] = 0;
}
}
}
if(zeroRow){
for(int n = 0; n < matrix[0].length; n++){
matrix[0][n] = 0;
}
}
if(zeroColumn){
for(int m = 0; m < matrix.length; m++){
matrix[m][0] = 0;
}
}
// int[] m = new int[matrix.length];
// int[] n = new int[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){
// if(m[i] != 1){
// m[i] = 1;
// }
// if(n[j] != 1){
// n[j] = 1;
// }
// }
// }
// }
// for(int i = 0; i < m.length; i++){
// if(m[i] == 1){
// for(int j = 0; j < matrix[0].length; j++){
// matrix[i][j] = 0;
// }
// }
// }
// for(int j = 0; j < n.length; j++){
// if(n[j] == 1){
// for(int i = 0; i < matrix.length; i++){
// matrix[i][j] = 0;
// }
// }
// }
}
}
没有评论:
发表评论