Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
解法二:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
解法一:
O(m*n)的方法不必说了。O(m+n)的思路就是借用两个vector,分别标注该行,该列有没有0。
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
vector<int> row_flags(m,0), col_flags(n,0);
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if (matrix[i][j]==0) {
row_flags[i] = 1;
col_flags[j] = 1;
}
}
}
for(int i=0; i<m; i++)
for(int j=0; j<n; j++){
if(row_flags[i]==1||col_flags[j]==1) matrix[i][j] = 0;
}
}
};
解法二:
延续上述的思路,那么我们不必要新建两个vector,然是直接借用原始matrix的第一行和第一列。
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
int row_flag = 0, col_flag = 0;
for(int j = 0; j<n; j++){
if(matrix[0][j]==0) row_flag = 1;
}
for(int i=0; i<m; i++){
if(matrix[i][0]==0) col_flag = 1;
}
for(int i = 1; i<m; i++)
for(int j=1; j<n; j++){
if(matrix[i][j]==0){
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
for(int i=1; i<m; i++)
for(int j=1; j<n; j++){
if(matrix[0][j]==0 || matrix[i][0]==0) matrix[i][j]=0;
}
if(row_flag){
for(int j=0; j<n; j++) matrix[0][j] = 0;
}
if(col_flag){
for(int i=0; i<m; i++) matrix[i][0] = 0;
}
}
};