【LeetCode】(73)Set Matrix Zeroes(Medium)

本文探讨了如何在常数空间复杂度下,通过利用矩阵的第一行和第一列来标记是否有零元素,从而实现矩阵中零元素的置零操作。详细介绍了两种解决方案,包括使用额外空间的方法和常数空间复杂度的方法,并提供了代码实现。

题目

Set Matrix Zeroes

  Total Accepted: 43426  Total Submissions: 137908 My Submissions

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?














解析


题目很简单,关键是需要空间尽量小,我使用了两个vector来保存行和列的有0的点。

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
          vector<int> colum;
		  vector<int> row;
		  for (int i = 0;i<matrix.size();i++)
		  {
			  bool flag = false;
			  for (int j = 0;j<matrix[0].size();j++)
			  {
				  if (matrix[i][j] == 0)
				  {
					  row.push_back(j);
					  flag = true;
				  }
			  }
			  if (flag)
				  colum.push_back(i);
		  }

		  for (int i = 0;i< colum.size();i++)
			  for (int j = 0;j<matrix[0].size();j++)
				  matrix[colum[i]][j] = 0;

		  for (int i = 0;i< matrix.size();i++)
			  for (int j = 0;j<row.size();j++)
				  matrix[i][row[j]] = 0;
    }
};

不过空间复杂度还是高了,看大神代码吧,其实思路也很简单,就是把第一行和第一列作为其他行列是否有0的记录,有的话就把第一行或者列相应位置也改成0 。最后再把除第一行和第一列以外的可以相应去赋为0,不过这个时候已经没有了第一行列是否有0 的记录了,所以要在一开始就做记录。

void setZeroes(vector<vector<int> > &matrix) 
{
    const size_t m = matrix.size();
    const size_t n = matrix[0].size();
    bool row_has_zero = false; // 第一行是否存在0
    bool col_has_zero = false; // 第一列是否存在0
    for (size_t i = 0; i < n; i++)
        if (matrix[0][i] == 0) 
        {
            row_has_zero = true;
            break;
        }
    for (size_t i = 0; i < m; i++)
        if (matrix[i][0] == 0) 
        {
            col_has_zero = true;
            break;
        }
    for (size_t i = 1; i < m; i++)
        for (size_t j = 1; j < n; j++)
            if (matrix[i][j] == 0) 
            {
                matrix[0][j] = 0;
                matrix[i][0] = 0;
            }
    for (size_t i = 1; i < m; i++)
        for (size_t j = 1; j < n; j++)
            if (matrix[i][0] == 0 || matrix[0][j] == 0)
                matrix[i][j] = 0;
    if (row_has_zero)
        for (size_t i = 0; i < n; i++)
            matrix[0][i] = 0;
    if (col_has_zero)
        for (size_t i = 0; i < m; i++)
            matrix[i][0] = 0;
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值