LeetCode解题 73:Set Matrix Zeroes
Problem 73: Set Matrix Zeroes [Medium]
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?
来源:LeetCode
解题思路
这道题做出来比较简单,主要是需要符合题目中in-place以及只使用常数空间的要求。那就想到利用已有的matrix空间,通过数组中的某一位做信息储存位(不需要额外空间),而省去记录哪些行哪些列需要置零的空间(复杂度为
O
(
m
+
n
)
O(m+n)
O(m+n))。
与Problem 41: First Missing Positive有共通之处,将第一行第一列用于记录信息,如果某数为0, 就将相应的第一行第一列中的数置0,最后统计时将第一行第一列中显示为0的整行整列都置0。第一行第一列的情况需要单独记录。
具体思路:
- 用两个flag分别记录第一行第一列中是否有零。
- 两次循环:
a. 第一次循环:遍历整个数组,若matrix[i][j] = 0,则令matrix[i][0] = 0,matrix[0][j] = 0,用于记录以后第i行第j列需要全部置零。
b. 第二次循环:遍历第一行第一列,将其中值为0的同一行列都置零。 - 根据flag的值决定第一行第一列本身是否都要置零。
整个算法时间复杂度为 O ( m ∗ n ) O(m*n) O(m∗n),空间复杂度为 O ( 1 ) O(1) O(1)。
运行结果:

Solution (Java)
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean flagrow = false;
boolean flagcol = false;
for(int j = 0; j < n; j++){
if(matrix[0][j] == 0) flagrow = true;
}
for(int i = 0; i < m; i++){
if(matrix[i][0] == 0) flagcol = true;
}
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
if(matrix[i][j] == 0){
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for(int j = 1; j < n; j++){
if(matrix[0][j] == 0){
for(int i = 1; i < m; i++){
matrix[i][j] = 0;
}
}
}
for(int i = 1; i < m; i++){
if(matrix[i][0] == 0){
for(int j = 1; j < n; j++){
matrix[i][j] = 0;
}
}
}
if(flagrow){
for(int j = 0; j < n; j++){
matrix[0][j] = 0;
}
}
if(flagcol){
for(int i = 0; i < m; i++){
matrix[i][0] = 0;
}
}
}
}
本文提供了一种解决LeetCode第73题SetMatrixZeroes的高效算法,采用原地操作和常数空间复杂度,通过利用矩阵的第一行和第一列作为标记位,避免了额外空间的使用。

被折叠的 条评论
为什么被折叠?



