LeetCode 73 _ Set Matrix Zeroes 给矩阵赋值0

Description: 

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

Example 1:

Input: 
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
Output: 
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]

Example 2:

Input: 
[
  [0,1,2,0],
  [3,4,5,2],
  [1,3,1,5]
]
Output: 
[
  [0,0,0,0],
  [0,4,5,0],
  [0,3,1,0]
]

Follow up:

  • 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?

 

 

Solution:

 这道题让我们将二维数组中含有0的行列里的所有数赋值为0

 

题目的最后还提到了对空间复杂度的要求,如果创造一个新的数组,并且对二维数组顺序遍历,按照题目要求填充新的数组,这样就是一个O(mn)的解法。

但是题目要求我们对空间复杂度进行优化,最终希望得到一个O(m+n)的算法,因此我们就要考虑在原数组的基础上进行操作了,不创造一个新的数组,这样子就可以降低空间复杂度了。

 

当检查到该行/列含有0时,需要使用一个标记来注明这一行/列中含有0;当检查完成后,再根据标记对数组进行操作。

一个很简易的方法是使用行头/列头作为标记,例如,若检查到该行含有0,则把该行的第一个数改为0,如此检查完所有数,

但是在检查的时候我们会发现,第一行与第一列都需要用到第一位的那个数字,这时我们该怎么办呢?可以自行再创建一个变量,初始值设为1,用于存储剩下的那一个标记,就可以避免冲突了。

遍历完成后,根据行头/列头与变量的值改变数组中元素的值。需要注意的是,应从尾部开始,因为头部是改变的标志,若先将行头修改,后面的数就都是零啦!就不能正确的修改了。

 

 

Code:

public void setZeroes(int[][] matrix) {
    int row = matrix.length, col = matrix[0].length;
    int overlap1 = 1;
    for (int i = 0; i < row; i++){
        if (matrix[i][0] == 0){
            overlap1 = 0;  // 记录第0列是否存在零,因为(0,0)位需要存放第0行
        }
        for (int j = 1; j < col; j++){
            if (matrix[i][j] == 0){
                matrix[i][0] = 0;
                matrix[0][j] = 0;
            }
        }               
    }

   for (int i = row-1; i >= 0; i--){  // 从后开始,因为第一排是判断的前提,先改会影响到后面的判断
        for (int j = col-1; j > 0 ; j--){
            if (matrix[i][0] == 0 || matrix[0][j] == 0){
                matrix[i][j] = 0;
            }
        }
        if (overlap1 == 0){
            matrix[i][0] = 0;
        }
    }
}

  

 

提交情况:

这个Memory Usage有点迷,我最开始测出来都是5%左右,试了多个标答都是这个结果。于是加上了0的判断,升到了57%,正当我惊叹边界对效率的提高时,我删去了边界判断,效率却变成了70%+……尽管一直知道这个值在浮动,但这个变化也太大,着实看不懂……_(:зゝ∠)_ 

 

Runtime: 1 ms, faster than 94.83% of Java online submissions for Set Matrix Zeroes.

Memory Usage: 50.5 MB, less than 5.10% of Java online submissions for Set Matrix Zeroes.

Memory Usage: 45.2 MB, less than 57.82% of Java online submissions for Set Matrix Zeroes.

Memory Usage: 44.2 MB, less than 71.94% of Java online submissions for Set Matrix Zeroes.

posted @ 2019-04-11 14:45  Doris7  阅读(164)  评论(0编辑  收藏  举报