public class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
Boolean[] rows = new Boolean[m];
Boolean[] cols = new Boolean[n];
for(int i = 0; i< m; i++){
for(int j = 0; j< n; j++){
if(matrix[i][j] == 0){
rows[i] = true;
cols[j] = true;
}
}
}
for(int i = 0; i<m; i++){
for(int j = 0; j< n; j++){
if(rows[i] ==true || cols[j] == true)
matrix[i][j] = 0;
}
}
}
}
该题是leetcode第73题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.
我的做法是,加一个行数组、一个列数组,来记录哪些行、哪些列有0,但是提交时出现了空指针错误。
你使用了Boolean定义你的M+N,默认初始化是null,换用boolean,默认初始化才是false。
然后解题思路优化上,题目提示了使用原地算法,
矩阵的第一行和第一列,其实是一个m+n,类似你的rows和cols。
优先判断第一行和第一列是否存在0,临时记录下
然后再判断x(x>0)行,y(y>0)列是否存在0,存在的更新他对应的第一行,第一列的值为0
最后根据临时的记录,和更新了的第一行第一列,更新整个矩阵,这样实际使用的额外空间,只有2个,是用来记录第一行和第一列是否存在0