题目:
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?
解答:
解法一:空间复杂度O(m+n)
思路:
- 创建两个boolean数组,遍历原二维数组,当当前元素为0时记录当前元素的行坐标及列左边
- 遍历两个boolean数组,当为true是表示当前行或者列中所有元素需要赋值为0
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean[] row = new boolean[m];
boolean[] column = new boolean[n];
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
if(matrix[i][j] == 0) {
row[i] = true;
column[j] = true;
}
}
}
for(int i=0; i<row.length; i++) {
for(int j=0; j<column.length; j++) {
if(row[i]) {
matrix[i][j] = 0;
} else if(column[j]) {
matrix[i][j] = 0;
}
}
}
return;
}
}
这种解法的时间复杂度为O(m*n),空间复杂度为O(m+n)
题目要求尽量采用空间复杂度为O(1)的解法,那么需直接修改原矩阵。
解法二:空间复杂度O(1)
看到了他人空间复杂度为O(1)的解法,思路为:遍历矩阵,当出现零时,将其对应的行、列的首位置零,作为标识,根据该标识后续将对应的行列置零即可。这个做法的好处是,标识占用的空间是原数组空间,且标识置位与m或n的长度无关,无需额外的时间复杂度。
- 当matrix[0][0]位置为零,表示第零行需要置零,零列置零需要额外的标志位zeroCol
- 遍历数组,先对第0列进行判断,若存在0则说明第0列需要置零,令zeroCol=true。
- 并对数组除去第0列的数进行遍历判断,若为零则将其对应的行、列首位置零
- 根据首行和首列的0标志位进行判断,对对应的行、列分别置零
- 最后对第零行和第零列进行置零。若matrix[0][0] == 0则说明第0行需要置零,若zeroCol为true则说明第0列需要置零
class Solution {
public void setZeroes (int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean zeroCol = false;
// 做标记
for (int i=0; i<m ; i++)
{
if (matrix[i][0] == 0) {
zeroCol = true; // 判断首列是否有零
}
for (int j=1; j<n; j++)
{
if (matrix[i][j] == 0)
{
matrix[i][0] = 0; // 行标记
matrix[0][j] = 0; // 列标记
}
}
}
// 根据标记写0
for (int i=1; i<m; i++)
{
for (int j=1; j<n; j++)
{
if (matrix[i][0] == 0 || matrix[0][j] == 0)
{
matrix[i][j] = 0;
}
}
}
// 最后处理零行
if (matrix[0][0] == 0)
{
for (int j=0; j <n; j++) {
matrix[0][j] = 0;
}
}
// 最后处理零列
if (zeroCol)
{
for (int i=0; i <m; i++) {
matrix[i][0] = 0;
}
}
}
}
算法的时间复杂度为O(m*n),空间复杂度为O(1)