Given am 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?
这道题是修改矩阵中数字0所在的行列数据为0,题目难度为Medium。
题目的关键在于in-place,所谓in-place,即要求空间复杂度为O(1),一般来说会使用已有的变量来存储中间变量和状态。
根据题目要求,需要统计所有的行和列是否有0存在,如果有0该行和该列即可全部修改为0,一般情况下需要O(m+n)的空间来存储状态。既然题目要求in-place,这里O(m+n)的空间就需要用原来矩阵的空间来存储,很自然我们会想到用一行和一列来记录下这些状态。这里我们用第一行来记录所有列中是否有0存在,用第一列来记录所有行中是否有0存在,同时问题来了,matrix[0][0]只能记录第一行或第一列的状态,因而我们需要额外的变量来记录另一个状态。代码中用firstRowHasZero来记录第一行是否有0,这样问题就迎刃而解了。具体代码:
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
if(matrix.empty()) return;
bool firstRowHasZero = false;
int row = matrix.size();
int col = matrix[0].size();
for(int i=0; i<col; ++i) {
if(!matrix[0][i]) {
firstRowHasZero = true;
break;
}
}
for(int i=1; i<row; ++i) {
for(int j=0; j<col; ++j) {
if(!matrix[i][j]) {
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for(int i=1; i<row; ++i) {
for(int j=col-1; j>=0; --j) {
if(!matrix[i][0] || !matrix[0][j]) {
matrix[i][j] = 0;
}
}
}
if(firstRowHasZero) {
for(int i=0; i<col; ++i) {
matrix[0][i] = 0;
}
}
}
};