73. Set Matrix Zeroes

Description

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

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?

Tags

Array

Solution

直接的解法(见解法2)是用两个分别与行和列等长的布尔数组标记对应行列是否存在0,再遍历一遍所有元素,检查其行列号在两数组的对应位置上是否已被标记,如果至少有一个被标记则修改该位置元素为0。

进阶的解法(见解法1)是采用第一行和第一列作为这两个数组,但考虑到二者可能自身就包含0,所以先使用两个布尔变量来记录二者是否含0。从下标(1, 1)开始做与上个解法相同的事。最后根据两个变量来判断是否要把第一行或第一列设置全0。

A simple solution is using 2 boolean arrays whose length equal to the rows and columns of the matrix respectively to mark the presence or absence of 0 in the corresponding row or column. Then traverse all elements and check if its row/col number is marked in the corresponding position of the two arrays. Set the current element to 0 if one of both positions is marked.

An advanced solution is to use the first row and column to substitute 2 arrays to save space. However, each of them might contains 0. Therefore, 2 boolean variables are used to record if the first row and column contain 0 before we perform the same solution.

Complexity

Solution 1:

  • Time complexity: O(mn)O(mn)

  • Space complexity: O(1)O(1)

Solution 2:

  • Time complexity: O(mn)O(mn)

  • Space complexity: O(m+n)O(m+n)

Code

Solution 1: Space complexity O(1) (2 variables)

Solution 2: Space complexity O(m+n) (2 arrays)

Reference

Last updated

Was this helpful?