描述
给定一个N阶方阵int[][](C++中为vector<vector><int>>)mat及其阶数n,若方阵中某个元素为0,则将其所在的行与列清零。返回改变后的int[][]方阵(C++中为vector<vector><int>>),保证n小于等于300,矩阵中的元素在nt范围内。</int></vector></int></vector>
测试样例:
[[1,2,3],[0,1,2],[0,0,1]]
返回:[[0,0,3],[0,0,0],[0,0,0]]
import java.util.*;
/*此方法空间复杂度O(m+n),时间复杂度O(m*n),首先找到需要变为0的行和列号,
记录在矩阵rowZeros和colZeros中,若需要变为0则记为1,反之记为0,最后清零
*/
public class Clearer {
public int[][] clearZero(int[][] mat, int n) {
// write code here
int M = mat.length;
int N = mat[0].length;
int[] rowZeros = new int[M];
int[] colZeros = new int[N];
for(int i = 0; i<M; i++){
for(int j = 0;j<N;j++){
if(mat[i][j]==0){
rowZeros[i] = 1;
colZeros[j] = 1;
}
}
}
for(int i=0;i<M;i++){
for(int j=0;j<N;j++){
if(rowZeros[i] == 1 || colZeros[j] == 1){
mat[i][j] = 0;
}
}
}
return mat;
}
}