[leetcode-73]Set Matrix Zeroes(C语言)

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?

首先,这道题要求用常数空间解决方案,这是比较难的,我之前所想到的也只是用栈,将元素为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;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值