文章作者:Tyan
博客:noahsnail.com | 优快云 | 简书
1. Description

2. Solution
- Version 1
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int rows = matrix.size();
if(rows == 0) {
return;
}
int columns = matrix[0].size();
vector<int> row;
vector<int> column;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
if(!matrix[i][j]) {
row.push_back(i);
column.push_back(j);
}
}
}
for(int i = 0; i < row.size(); i++) {
for(int j = 0; j < columns; j++) {
matrix[row[i]][j] = 0;
}
}
for(int j = 0; j < column.size(); j++) {
for(int i = 0; i < rows; i++) {
matrix[i][column[j]] = 0;
}
}
}
};
- Version 2
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int rows = matrix.size();
if(rows == 0) {
return;
}
int columns = matrix[0].size();
bool row = false;
bool column = false;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
if(!matrix[i][j]) {
if(!i) {
row = true;
}
if(!j) {
column = true;
}
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for(int i = 1; i < rows; i++) {
for(int j = 1; j < columns; j++) {
if(!matrix[0][j] || !matrix[i][0]) {
matrix[i][j] = 0;
}
}
}
if(row) {
for(int j = 0; j < columns; j++) {
matrix[0][j] = 0;
}
}
if(column) {
for(int i = 0; i < rows; i++) {
matrix[i][0] = 0;
}
}
}
};
本文介绍了解决矩阵中置零问题的两种方法。一种是使用额外的行和列数组来记录需要置零的位置,另一种是在矩阵的第一行和第一列中直接进行标记,避免了额外的空间消耗。通过这两种方法,可以有效地将包含零元素的行和列全部置零。
419

被折叠的 条评论
为什么被折叠?



