Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:Did you use extra space?A straight forward solution using O(mn) space is probably a bad idea.A simple improvement uses O(m + n) space, but still not the best solution.Could you devise a constant space solution?
Solution1:Extra 行Mark数组 + 列Mark数组
思路:
Time Complexity: O(MN) Space Complexity: O(M + N)
Solution2:本身第一行/第一列作为行Mark数组 + 列Mark数组
思路: 将本身第一行/第一列作为行Mark数组 + 列Mark数组,额外两个变量first_row_mark / first_col_mark 作为第一行/第一列的mark。
Time Complexity: O(MN) Space Complexity: O(1)
Solution1 Code:
class Solution {
public void setZeroes(int[][] matrix) {
boolean[] row_mark = new boolean[matrix.length];
boolean[] col_mark = new boolean[matrix[0].length];
// when matrix[row][col] == 0, mark it on row_mark or col_mark.
for(int row = 0; row < matrix.length; row++) {
for(int col = 0; col < matrix[0].length; col++) {
if(matrix[row][col] == 0) {
row_mark[row] = true;
col_mark[col] = true;
}
}
}
// set row or col to 0 based on mark arrays.
for(int i = 0; i < row_mark.length; i++) {
if(row_mark[i] == true) {
for(int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = 0;
}
}
}
for(int i = 0; i < col_mark.length; i++) {
if(col_mark[i] == true) {
for(int j = 0; j < matrix.length; j++) {
matrix[j][i] = 0;
}
}
}
}
}
Solution2 Code:
public class Solution {
public void setZeroes(int[][] matrix) {
boolean first_row_mark = false, first_col_mark= false;
// when matrix[row][col] == 0, mark it on row_mark(first row here) or col_mark(first column here).
for(int row = 0; row < matrix.length; row++) {
for(int col = 0; col < matrix[0].length; col++) {
if(matrix[row][col] == 0) {
if(row == 0) first_row_mark = true;
else if(col == 0) first_col_mark = true;
matrix[0][col] = 0;
matrix[row][0] = 0;
}
}
}
for(int row = 1; row < matrix.length; row++) {
for(int col = 1; col < matrix[0].length; col++) {
if(matrix[row][0] == 0 || matrix[0][col] == 0) {
matrix[row][col] = 0;
}
}
}
if(first_row_mark) {
for(int j = 0; j < matrix[0].length; j++) {
matrix[0][j] = 0;
}
}
if(first_col_mark) {
for(int i = 0; i < matrix.length; i++) {
matrix[i][0] = 0;
}
}
}
}