编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。
示例 1:
输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
示例 2:
输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
class Solution {
public void setZeroes(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return;
}
HashSet<String> hashSet = new HashSet<>();
for(int i= 0; i< matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
if(matrix[i][j] == 0){
hashSet.add(i + ":" + j);
}
}
}
for(String cur: hashSet){
int i = Integer.parseInt(cur.split(":")[0]);
int j = Integer.parseInt(cur.split(":")[1]);
for(int row = 0; row < matrix.length; row ++){
matrix[row][j] = 0;
}
for(int col = 0; col < matrix[0].length; col ++){
matrix[i][col] = 0;
}
}
}
}
这样处理的时间复杂度较高,可以同时在第一行第一列进行位置的记录,然后遍历每个元素,如果该元素位置的第一行或者第一列是0,那么就将该元素置零,之后,再统计第一行第一列的0的情况,如果有0那么就将第一行或者第一列全部置零即可。