Given a mxn matrix, if an element is 0, set its entire row and column to 0.
Do it in-place?
[
[1,11, 1,1]
[2, 3, 4,0]
[5, 6, 19,8]
]
=>
[
[1,11 ,1 ,0]
[0, 0 ,0 ,0]
[5, 6, 19,0]
]
[
[1,11, 1,0]
[2, 3, 4,0]
[5, 6, 19,8]
]
=>
[
[0,0 , 0,0]
[2, 3, 4,0]
[5, 6, 19,0]
]
=>
[
[0,0 , 0,0]
[0, 0, 0,0]
[0, 0, 0,0]
]
=> WRONG, cannot set matrix zero in serial order
2. Implementation
do a statistics to collect which row or index has zero and set the zeroes in a batch according to statistics table
Q1: how to form a such table ?
A1: keep two boolean array for row and column like row[m] and col[n]
Q1: how to form a such table without Extra space?
A1: use the the first row and the first column as row[m] = matrix[i][0]
and col[n] = matrix[0][i]
Q1: What about first column or first row has zero by itself?
A1: use two boolean flag to record
// Time :O(mxn) over the matrix, Space:O(1) two flag
public void setZeroes (int[][] matrix)
{
// validate the input
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
{
return;
}
boolean fstRowWithZero = false;
boolean fstColWithZero = fasle;
for (int i = 0 ; i < matrix. length;i++)
{
if (matrix[i][0] == 0)
{
fstColWithZero = true;
// NOTE:
break;
}
}
for (int j = 0 ; j < matrix[0].length;j++)
{
if (matrix[0][j] == 0)
{
fstRowWithZero = true;
// NOTE:
break;
}
}
// NOTE: start from second row and column
//for ( int i = 0 ; i < matrix.length;i++)
for ( int i = 1 ; i < matrix.length;i++)
{
//for (int j = 0 ; j < matrix[0].length ; j++)
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 = 0 ; i < matrix.length;i++)
{
for ( int j = 0 ; j < matrix[0].length ;j++)
{
if ( matrix[i][0] == 0 || matrix[i][j] == 0 )
{
matrix[i][j] = 0;
}
}
}
if (fstRowWithZero == true)
{
for (int j = 0 ; j< matrix[0].length;j++)
{
matrix[0][j] = 0;
}
}
if (fstColWithZero == true)
{
for (int i = 0 ; i < matrix.length;i++)
{
matrix[i][0] = 0;
}
}
}
3. Similar OnesRotate Image
Search a 2D matrix
Spiral Matrix
Spiral Matrix II
No comments:
Post a Comment