Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
click to show follow up.
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?
给定一个m*n的矩阵,如果一个元素为0,那么就让这个元素所在行和列都变成0,要求空间复杂度为o(1)。
1、暴力的做法就是再设定一个一样的矩阵,每次遇到0,然后将第二个矩阵的相应位置置0,空间复杂度为O(mn)。
2、然后略微优化就是每次遇到0的时候,记录需要置0的行号和列号,空间复杂度为O(m+n)。
3、如果要求空间复杂度为1,其实只需要将2中记录的方法,记录在第0行和第0列就行了。
注意:在处理的时候,注意分清行和列。并且是从第一行的元素开始,注意下标的起始位置。
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
int rows = matrix.size();
int cols = matrix[0].size();
if(rows == 0 || cols == 0)
return;
bool rowflage = false;
bool colflage = false;
int i=0;
int j=0;
//判断第0行是否有0
for(j=0; j<cols; j++){
if(matrix[0][j] == 0)
rowflage = true;
}
//判断第0列是否有0
for(i=0; i<rows; i++){
if(matrix[i][0] == 0)
colflage = true;
}
//标记数组元素
for(i=1; i<rows; i++){
for(j=1; j<cols; j++){
if(matrix[i][j] == 0){
//某一个元素为0
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
//根据标记数组将第i行的所有元素置为0
for(i=1; i<rows; i++){
if(matrix[i][0] == 0){
for(int k=1; k<cols; k++)
matrix[i][k]=0;
}
}
for(j=1; j<cols; j++){
if(matrix[0][j] == 0){
for(int k=1; k<rows; k++)
matrix[k][j]=0;
}
}
//第一行元素为0
if(rowflage){
for(j=0; j<cols; j++){
matrix[0][j]=0;
}
}
if(colflage){
for(i=0; i<rows; i++){
matrix[i][0]=0;
}
}
}
};