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?
由于有空间复杂度的限制,要求用常量存储空间,所以只能借助已有的矩阵存储空间,只生成有限个变量来辅助解决问题。可以用借助矩阵的第一行和第一列来存储标志信息(这一行这一列是否有0存在),先把第一行第一列之外的元素处理完,再来判断第一行第一列中是否有0存在,如果有的话,就将第一行或者第一列元素全部清0。
public class Solution {
public void setZeroes(int[][] matrix) {
if(matrix.length<=0) return;
boolean firstrow = false;
boolean firstcol = false;
//检测第一行元素中是否有0出现
for(int i=0;i<matrix[0].length;i++) {
if(matrix[0][i]==0) {
firstrow = true;
}
}
//检测第一列元素中是否有0出现
for(int i=0;i<matrix.length;i++) {
if(matrix[i][0]==0) {
firstcol = true;
}
}
//检测其他行和其他列中是否有0出现
for(int i=1;i<matrix.length;i++) {
for(int j=1;j<matrix[0].length;j++) {
if(matrix[i][j]==0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
//将第一行第一列以外的元素先清0
for(int i=1;i<matrix.length;i++) {
for(int j=1;j<matrix[0].length;j++) {
if(matrix[i][0]==0 || matrix[0][j]==0) {
matrix[i][j] = 0;
}
}
}
//判读第一行中是否有0元素
if(firstrow) {
for(int i=0;i<matrix[0].length;i++) {
matrix[0][i] = 0;
}
}
//判断第一列中是否有0元素
if(firstcol) {
for(int i=0;i<matrix.length;i++) {
matrix[i][0] = 0;
}
}
}
}