Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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,代码如下:
void setZeroes(int** matrix, int matrixRowSize, int matrixColSize) {
int row,col;
stack<int> rowStack;
stack<int> colStack;
for(row = 0;row<matrixRowSize;row++){
for(col = 0;col<matrixColSize;col++){
if(matrix[row][col] == 0){
rowStack.push(row);
colStack.push(col);
}
}
}
while(!rowStack.empty()){
row = rowStack.top();
rowStack.pop();
memset(matrix[row],0,sizeof(int)*matrixColSize);
}
while(!colStack.empty()){
col = colStack.top();
colStack.pop();
for(row = 0;row<matrixRowSize;row++)
matrix[row][col] = 0;
}
}
但是使用栈空间复杂度为O(m+n),不大符合要求。
题目要求常数空间复杂度,这里只有2种情况,第一,是可以用常数个大小来存储所需要的信息;第二,是原来存储空间足够稀疏,来存储新的信息。这里满足第二条。简单的思路是将上面的栈换成原来矩阵的某一行某一列,典型的,第一行第一列。
某个元素(row,col)为0,将对应的(row,0)和(0,col)设为0。然后最后检索第一行和第一列来对矩阵进行处理。
那将第一行第一列覆盖之后,会不会产生信息丢失?如果该位置原来元素为0,那么会丢失,如果不是0,那不会产生丢失,因为这一列(行)将被设为0,所以无所谓。那如果为0的时候为什么会丢失信息?因为原始为0与后覆盖为0的处理不大一样。
所以需要先判断第一行和第一列是否有为0的情况,如果有,将其进行特殊处理。代码如下:
void setZeroes(int** matrix, int matrixRowSize, int matrixColSize) {
int row,col;
bool firstRow = false,firstCol = false;
if(matrixRowSize<=0||matrixColSize<=0)
return;
//查看firstRow
for(col = 0;col<matrixColSize;col++){
if(matrix[0][col] == 0){
firstRow = true;
break;
}
}
for(row = 0;row<matrixRowSize;row++){
if(matrix[row][0] == 0)
{
firstCol = true;
break;
}
}
for(row = 0;row<matrixRowSize;row++){
for(col = 0;col<matrixColSize;col++){
if(matrix[row][col] == 0){
matrix[row][0] = 0;
matrix[0][col] = 0;
}
}
}
for(row = 1;row<matrixRowSize;row++){
if(matrix[row][0] == 0){
memset(matrix[row],0,sizeof(int)*matrixColSize);
}
}
for(col = 1;col<matrixColSize;col++){
if(matrix[0][col] == 0){
for(row = 0;row<matrixRowSize;row++){
matrix[row][col] = 0;
}
}
}
if(firstRow){
memset(matrix[0],0,sizeof(int)*matrixColSize);
}
if(firstCol){
for(row = 0;row<matrixRowSize;row++)
matrix[row][0] = 0;
}
}