Idea: First check whether the first row and the first column has zeros. Then use the first row and the first column as the buffer. If the matrix[i][j]==0 (i>=1, j>=1), set matrix[i][0] and matrix[0][j]=0. Then set each row i to zeros if matrix[i][0]==0, set each column j to zeros if matrix[0][j]==0. At last, set the first row and the first column to zeros according to the results of first step.
Time: O(n^2) Space: O(1)
Code:
public class Solution {
public void setZeroes(int[][] matrix) {
boolean rowHasZero=false;
boolean columnHasZero=false;
for(int i=0;i<matrix.length;i++)
{
if(matrix[i][0]==0)
{
columnHasZero=true;
break;
}
}
for(int j=0;j<matrix[0].length;j++)
{
if(matrix[0][j]==0)
{
rowHasZero=true;
break;
}
}
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;
}
}
}
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;
}
}
if(rowHasZero)
{
for(int j=0;j<matrix[0].length;j++)
matrix[0][j]=0;
}
if(columnHasZero)
{
for(int i=0;i<matrix.length;i++)
matrix[i][0]=0;
}
}
}
No comments:
Post a Comment