Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Solution1:
O(n) 空间复杂度: 先扫描一遍matrix,记录存在0的行和列,最后再将这些行和列进行赋值0。
class Solution {
private:
void setRow(vector<vector<int>>& matrix, int row) {
for (int i = 0; i < matrix[0].size(); i++) {
matrix[row][i] = 0;
}
}
void setCol(vector<vector<int>>& matrix, int col){
for (int i = 0; i < matrix.size();i++) {
matrix[i][col] = 0;
}
}
public:
void setZeroes(vector<vector<int>>& matrix) {
//sanity check
if (matrix.size() == 0 || matrix[0].size() == 0) return;
set<int> col;
set<int> row;
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[0].size(); j++) {
if (matrix[i][j] == 0) {
if (col.find(j) == col.end()) {
col.insert(j);
}
if (row.find(i) == row.end()) {
row.insert(i);
}
}
}
}
for (set<int> :: iterator it = col.begin(); it != col.end(); it++){
setCol(matrix, *it);
}
for (set<int> :: iterator it = row.begin(); it != row.end(); it++) {
setRow(matrix, *it);
}
return;
}
};
Solution2:
对空间复杂度可以进一步优化: O(1) 利用当前matrix的第一行和第一列来记录置0的情况,如果扫描到一个0,就把当前的第一行上的那列置0,把当前的第一列的那行置0,最后再扫描一遍,将所有第一列和第一行的所有0所在列和行置0.对于第一列和第一行可以利用两个变量来看是否要全置0,这样做的空间复杂度为O(1)
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
//sanity check
if (matrix.size() == 0 && matrix[0].size() == 0) {
return;
}
bool row = false;
bool col = false;
for (int i = 0; i < matrix.size(); i++) {
if (matrix[i][0] == 0) {
col = true;
break;
}
}
for (int i = 0; i < matrix[0].size(); i++) {
if (matrix[0][i] == 0){
row = true;
break;
}
}
for (int i = 1; i < matrix.size(); i++) {
for (int j = 1; j < matrix[0].size(); j++) {
if (matrix[i][j] == 0) {
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for (int i = 1; i < matrix.size(); i++) {
for (int j = 1; j < matrix[0].size(); j++) {
if (matrix[0][j] == 0 || matrix[i][0] == 0) {
matrix[i][j] = 0;
}
}
}
if (col) {
for (int i = 0; i < matrix.size(); i++){
matrix[i][0] = 0;
}
}
if (row) {
for (int i = 0; i < matrix[0].size(); i++) {
matrix[0][i] = 0;
}
}
return;
}
};
No comments:
Post a Comment