LeetCode 73 Set Matrix Zeroes(设矩阵元素为0)(Array)(*)

翻译

给定一个 m x n的矩阵matrix,如果其中一个元素为0,那么将其所在的行和列的元素统统设为0。要求就地计算。

跟进:

你使用了额外的空间吗?

一个直接的解决方案是使用 O(mn) 的空间,但这不是个好主意。
一个简单的改进是使用 O(m+n) 的空间,但这任然不是最好的解决方案。
你可以设计一个用常量空间的方案吗?

原文

Given a m 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?

分析

第一种使用 O(mn) 空间的方法倒是很简单,用二位数组存储需要转换为0的所有元素的坐标,最后统一刷新就好。

void setZeroes(vector<vector<int> >& matrix) {
  vector<vector<int> > zeroes;

  for (int i = 0; i < matrix.size(); i++) {
    for (int j = 0; j < matrix[i].size(); j++) {
      if (matrix[i][j] == 0) {
    vector<int> zero;
    zero.push_back(i);
    zero.push_back(j);
    zeroes.push_back(zero);
      }
    }
  }
  for (int i = 0; i < zeroes.size(); i++) {
    for (int col = 0; col < matrix[zeroes[i][0]].size(); col++) {
      matrix[zeroes[i][0]][col] = 0;
    }
    for (int row = 0; row < matrix.size(); row++) {
      matrix[row][zeroes[i][1]] = 0;
    }
  }
}

第二种是分别记录所有等于0的元素的横坐标和纵坐标。

void setZeroes(vector<vector<int> >& matrix) {
  vector<int> rows, cols;
  int rowLen = matrix.size(), colLen = matrix[0].size();

  for (int r = 0; r < rowLen; r++) {
    for (int c = 0; c < colLen; c++) {
      if (matrix[r][c] == 0) {
    rows.push_back(r);
    cols.push_back(c);
      }
    }
  }

  for (int i = 0; i < rows.size(); i++) {
    for (int im = 0; im < colLen; im++) {
      matrix[rows[i]][im] = 0;
    }
  }
  for (int j = 0; j < cols.size(); j++) {
    for (int jm = 0; jm < rowLen; jm++) {
      matrix[jm][cols[j]] = 0;
    }
  }
}

第三种方法就是通过一个值来记录一个维度。也就是说如果某行的第一列的值等于0,就将这个值标记为0,到时候直接把这一整行都置为0。它的好处在于,等你在遍历整个二维数组的时候,你可以随意的设置第一列在各行的值,而不至于在后续的遍历中产生副作用。

也就是说,可能你是 matrix[3][4]=0 ,也就是第三行第四列等于0,那么你可以把第四列的第一行那个值设为0,同时把第三行的第一列的值也设为0,但在下一次遍历的时候,因为第三行第一列为0了,你可以把整个第一列都置为0,所以用一个值来维护这一列的状态。代码在下文(2016/09/24)。

代码

Java

updated at 2016/09/04
    public void setZeroes(int[][] matrix) {
        int col0 = 1, rows = matrix.length, cols = matrix[0].length;

        for (int i = 0; i < rows; i++) {
            if (matrix[i][0] == 0) col0 = 0;
            for (int j = 1; j < cols; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = matrix[0][j] = 0;
                }
            }
        }

        for (int i = rows - 1; i >= 0; i--) {
            for (int j = cols - 1; j >= 1; j--) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
            if (col0 == 0) matrix[i][0] = 0;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值