
题解:这道题不能直接双层遍历遇到0就开始行列置零,会影响下次循环遍历。所以可以通过两个集合来记录0所在的行和列,然后再双层遍历遇到标记置0,代码如下:
java
class Solution {
public void setZeroes(int[][] matrix) {
if (matrix==null||matrix.length==0){
return;
}
Set<Integer> xSet = new HashSet<>();
Set<Integer> ySet = new HashSet<>();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j]==0){
xSet.add(i);
ySet.add(j);
}
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (xSet.contains(i)||ySet.contains(j)){
matrix[i][j]=0;
}
}
}
}
}