Question
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
本题难度Medium。
集合法
【复杂度】
时间 O(MN) 空间 O(1)
【思路】
如果matrix[i][j]==0
,那么就对其所在的行列上的元素置0。不过要注意这里仅对该元素的上面和左边的元素置0,对于下面的和右边的不进行置0而是将其行列分别存入Set中。原因在于上面和左边的元素置0不会对后面的判断有影响,而下面的和右边的元素原本可能不是0,这下你置0了就会产生错判(新的置0元素并不会导致对其所在的行列上的元素置0)。例如:
input:
0 0 0 5
4 3 1 4
0 1 1 4
1 2 1 3
对于matrix[0][0]==0,那么如果将该行列元素全部置0:
0 0 0 0
0 3 1 4
0 1 1 4
0 2 1 3
然后matrix[1][0]==0,matrix[2][0]==0,matrix[3][0]==0
导致:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
【注意】
本题要求:Do it in place.
【代码】
public class Solution {
public void setZeroes(int[][] matrix) {
//require
int m=matrix.length;
if(m<1)
return;
int n=matrix[0].length;
Set<Integer> rowSet=new HashSet<Integer>(),colSet=new HashSet<Integer>();
//invariant
for(int i=0;i<m;i++)
for(int j=0;j<n;j++){
if(matrix[i][j]==0){
for(int x=0;x<i;x++)
matrix[x][j]=0;
for(int x=0;x<j;x++)
matrix[i][x]=0;
rowSet.add(i);colSet.add(j);
}else{
if(rowSet.contains(i)||colSet.contains(j))
matrix[i][j]=0;
}
}
}
}