Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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?
官方思路如下:
My idea is simple: store states of each row in the first of that row, and store states of each column in the first of that column. Because the state of row0 and the state of column0 would occupy the same cell, I let it be the state of row0, and use another variable "col0" for column0. In the first phase, use matrix elements to set states in a top-down way. In the second phase, use states to set matrix elements in a bottom-up way.
每次遇到一个0,就将该0对应的行的第一列和对应的列的第一行标志为0,最后统一处理,注意第一列即可。
public void setZeroes(int[][] matrix) {
boolean isZero=false;
for(int i=0;i<matrix.length;i++)
{
if(matrix[i][0]==0)isZero=true;
for(int j=1;j<matrix[0].length;j++)
{
if(matrix[i][j]==0)
{
matrix[i][0]=matrix[0][j]=0;
}
}
}
for(int i=matrix.length-1;i>=0;i--)
{
for(int j=matrix[0].length-1;j>=1;j--)
{
if(matrix[i][0]==0||matrix[0][j]==0)
{
matrix[i][j]=0;
}
}
if(isZero)
{
matrix[i][0]=0;
}
}
}