Solution1:我的答案
空间复杂度比较高,垃圾算法
class Clearer {
public:
vector<vector<int> > clearZero(vector<vector<int> > mat, int n) {
// write code here
vector<vector<int> > mat_copy = mat;
if(n == 0) return mat_copy;
set<int> row_zero, col_zero;
for(int i = 0; i < mat.size(); i++) {
for(int j = 0; j < mat[i].size(); j++) {
if(mat[i][j] == 0) {
if(row_zero.find(i) == row_zero.end()) {
clearRow(mat_copy, i);
row_zero.insert(i);
}
if(col_zero.find(j) == col_zero.end()) {
clearCol(mat_copy, j);
col_zero.insert(j);
}
}
}
}
return mat_copy;
}
void clearRow(vector<vector<int> > &mat, int r) {
for(int j = 0; j < mat[r].size(); j++) {
mat[r][j] = 0;
}
return;
}
void clearCol(vector<vector<int> > &mat, int c) {
for(int i = 0; i < mat.size(); i++) {
mat[i][c] = 0;
}
return;
}
};
Solution2:
记录下所有含0的行列值,再遍历。代码比较简练,学习之!
class Clearer {
public:
vector<vector<int> > clearZero(vector<vector<int> > mat, int n) {
// write code here
vector<bool> row(n, false);
vector<bool> column(n, false);
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(mat[i][j] == 0){
row[i] = true;
column[j] = true;
}
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(row[i] || column[j]){
mat[i][j] = 0;
}
}
}
return mat;
}
};