Set Matrix Zeroes

Problem

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:

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?

Analysis

O(mn)的空间解法最直接暴力,就是开辟和输入matrix同等大小的matrix,用来存储新的matrix;

O(m + n)的空间复杂度则是一个提升,考虑到问题的本质其实是对于为0的元素,其对应下标(i, j)对应的行和列需要被记录,因此分别使用 m, n空间记录那些行和列中有0;

O(1)的空间复杂度则需要思考如何利用matrix本身来存储某行某列有0元素的情况,这里就是想到了使用首行matrix[0][j]和首列matrix[i][0]作为存储该行i 或者该列j 是否应该设为0的状态的空间,同时安排额外两个变量记录首行和首列本身是否应该设为全0.

Code

Last updated

Was this helpful?