Set Matrix Zeroes
leetcode73
题目:
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(m**n) 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) 或 O(m+n) 比较容易实现,难度在于实现空间复杂度 O(1) 的算法。
思路:
空间复杂度 O(1) 代表我们不能创建行/列长度的状态数组,考虑借用输入数组存放状态变量。例如,选取第1列存放状态变量,在这之前先将第一列的状态保存下来。
class Solution {
public void setZeroes(int[][] matrix) {
// col0用来保存第一列状态
int col0 = 1;
int rows = matrix.length;
int cols = matrix[0].length;
for (int row = 0; row < rows; row++) {
if(matrix[row][0] == 0)
col0 = 0;
for(int col = 1; col < cols; col++){
// 将状态保存到第一列
if(matrix[row][col] == 0){
matrix[row][0] = 0;
matrix[0][col] = 0;
}
}
}
for (int row = rows-1; row >= 0 ; row--) {
for (int col = cols-1; col >= 1 ; col--) {
if(matrix[0][col] == 0 || matrix[row][0] == 0)
matrix[row][col] = 0;
}
// 还原第一列状态
if(col0 == 0)
matrix[row][0] = 0;
}
return;
}
}
算法只创建了常数个变量,空间复杂度为 O(1)