0073.矩阵置零
方法一:使用两个标记变量
时间复杂度 $O(m \times n)$,空间复杂度 $O(1)$,m
,n
分别表示 matrix
的行数和列数。
func setZeroes(matrix [][]int) {
m, n, zero_r, zero_c := len(matrix), len(matrix[0]), false, false
for i := 0; i < m; i++ {
if matrix[i][0] == 0 {
zero_r = true
break
}
}
for i := 0; i < n; i++ {
if matrix[0][i] == 0 {
zero_c = true
break
}
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
if matrix[i][j] == 0 {
matrix[i][0], matrix[0][j] = 0, 0
}
}
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
if matrix[i][0] == 0 || matrix[0][j] == 0 {
matrix[i][j] = 0
}
}
}
for i := 0; i < m && zero_r; i++ {
matrix[i][0] = 0
}
for i := 0; i < n && zero_c; i++ {
matrix[0][i] = 0
}
}
impl Solution {
pub fn set_zeroes(matrix: &mut Vec<Vec<i32>>) {
use std::cmp::{max, min};
let (m, n, mut zero_r, mut zero_c) = (matrix.len(), matrix[0].len(), false, false);
for i in 0..max(m, n) {
if matrix[min(i, m - 1)][0] == 0 {
zero_r = true;
}
if matrix[0][min(i, n - 1)] == 0 {
zero_c = true;
}
}
for i in 1..m {
for j in 1..n {
if matrix[i][j] == 0 {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for i in 1..m {
for j in 1..n {
if matrix[i][0] == 0 || matrix[0][j] == 0 {
matrix[i][j] = 0;
}
}
}
for i in 0..m {
if zero_r {
matrix[i][0] = 0;
}
}
for j in 0..n {
if zero_c {
matrix[0][j] = 0;
}
}
}
}