Set Matrix Zeroes

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

给定一个m * n的矩阵,如果一个元素为0,那么把这个元素所在的行和列都设置为0。我们可以借助两个boolean数组,一个代表行row,一个代表列col。遍历数组,如果遇到元素matrix[i][j]为0,就把相应的行row[i]设置为true; 相应的列col[j]设置为true。最后遍历这两个boolean数组,当遇到true时(row[i] == true || col[j] == true)就把当前元素设置为0。空间复杂度为O(m+n)。代码如下:

public class Solution {
public void setZeroes(int[][] matrix) {
if(matrix == null || matrix.length == 0)
return;
int m = matrix.length;
int n = matrix[0].length;
boolean[] row = new boolean[m];
boolean[] col = 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;
col[j] = true;
}
}

for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++) {
if(row[i] == true || col[j] == true)
matrix[i][j] = 0;
}
}
}


还有一种优化的方法可以把空间复杂度优化为O(1), 代码如下:

public class Solution {
public void setZeroes(int[][] matrix) {
if(matrix == null || matrix.length == 0) return;
int m = matrix.length;
int n = matrix[0].length;
boolean row = false, col = false;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++) {
if(matrix[i][j] == 0) {
if(i == 0) {
row = true;
} else if(j == 0){
col = true;
} else {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for(int i = m - 1; i >= 0; i--)
for(int j = n - 1; j >= 0; j--) {
if(i == 0 && row == true || j == 0 && col == true || matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值