问题描述
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
click to show follow up.
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?
问题分析
这题直接暴力的话至少需要四重循环,时间复杂度至少是O(m^2 n^2),使用辅助空间的话至少要O(m+n)
下面的解法使用第一行和第一列进行记录,若遍历数组时发现了0,那么它所在的第一行和第一列的相关元素就会被置零,最后再遍历一遍第一行和第一列,发现零元素了把所在行或列全部置零。
对于第一行和第一列,用一个boolean标记是否存在0,若存在,在解法最后将这行或列置零即可,时间复杂度O(mn),空间复杂度O(1)
代码实现
public void setZeroes(int[][] matrix) {
boolean hasZeroInRow = false;
boolean hasZeroInCol = false;
int row = matrix.length;
int col = matrix[0].length;
for (int i = 0; i < row; i++) {
if (matrix[i][0] == 0) {
hasZeroInCol = true;
break;
}
}
for (int i = 0; i < col; i++) {
if (matrix[0][i] == 0) {
hasZeroInRow = true;
break;
}
}
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
if (matrix[i][j] == 0) {
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
if (hasZeroInCol) {
for (int i = 0; i < row; i++) {
matrix[i][0] = 0;
}
}
if (hasZeroInRow) {
for (int i = 0; i < col; i++) {
matrix[0][i] = 0;
}
}
}
网友评论