编写一种算法,若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]
]
集合,
首先应该想到此题不能直接遍历,然后设置相应的行列为0。因为后续坐标点的0可能是前面新添加得来的,所以很可能导致整个数组全为0。
为了避免行列重复的情况,使用了两个unordered_set
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
unordered_set<int> rows;
unordered_set<int> cols;
for (int i = 0; i < matrix.size(); ++i) {
for (int j = 0; j < matrix[0].size(); ++j) {
if (matrix[i][j] == 0) {
rows.insert(i);
cols.insert(j);
}
}
}
for (int row : rows) {
for (int col = 0; col < matrix[0].size(); col++) {
matrix[row][col] = 0;
}
}
for (int col : cols) {
for (int row = 0; row < matrix.size(); row++) {
matrix[row][col] = 0;
}
}
}
};
时间复杂度: O(n^2)
空间复杂度: O(sqrt(n))
思路一致,不同之处用了bool数组替换了上述的unordered_set集合。
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int mRow = matrix.size();
int mCol = matrix[0].size();
if(mRow == 0 || mCol == 0) {
return;
}
vector<bool> row(mRow, false);
vector<bool> col(mCol, false);
for(int i = 0; i < mRow; i++) {
for(int j = 0; j < mCol; j++) {
if(matrix[i][j] == 0) {
row[i] = true;
col[j] = true;
}
}
}
for(int i = 0; i < mRow; i++) {
for(int j = 0; j < mCol; j++) {
if(row[i] || col[j]) {
matrix[i][j] = 0;
}
}
}
return;
}
};
作者:cui-tian-xiao
链接:https://leetcode-cn.com/problems/zero-matrix-lcci/solution/cjie-fa-ling-ju-zhen-9kai-pi-xin-bu-er-shu-zu-by-c/
来源:力扣(LeetCode)
时间复杂度: O(n^2)
空间复杂度: O(sqrt(n))
跟第一次解法一致。
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
unordered_set<int> rows;
unordered_set<int> cols;
for (int i = 0; i < matrix.size(); ++i) {
for (int j = 0; j < matrix[0].size(); ++j) {
if (matrix[i][j] == 0) {
rows.insert(i);
cols.insert(j);
}
}
}
for (int row : rows) {
for (int col = 0; col < matrix[0].size(); ++col) {
matrix[row][col] = 0;
}
}
for (int col : cols) {
for (int row = 0; row < matrix.size(); ++row) {
matrix[row][col] = 0;
}
}
}
};
时间复杂度: O(n^2)
空间复杂度: O(sqrt(n))
原文:https://www.cnblogs.com/phonyhao/p/14170595.html