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]
]
思路:终极follow up是是否用O(1)space来做,思路就是,利用第一行和第一列还记录为0的信息,然后用两个变量hold住第一行和第一列是否需要变为0。然后扫描中间的matrix,如果对应行或者列,在第一行和第一列上是0,那么设置成0,然后再判断第一行和第一列是否需要清空;
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean firstrow = false;
boolean firstcol = false;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(matrix[i][j] == 0) {
if(i == 0) {
firstrow = true;
}
if(j == 0) {
firstcol = true;
}
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for(int i = 1; i < m; i++) {
for(int j = 1; j < n; j++) {
if(matrix[0][j] == 0 || matrix[i][0] == 0) {
matrix[i][j] = 0;
}
}
}
if(firstrow) {
for(int j = 0; j < n; j++) {
matrix[0][j] = 0;
}
}
if(firstcol) {
for(int i = 0; i < m; i++) {
matrix[i][0] = 0;
}
}
}
}
思路:用row和col array来记录0的位置,然后再进行赋值0;
class Solution {
public void setZeroes(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return;
}
int n = matrix.length;
int m = matrix[0].length;
int[] row = new int[n];
int[] col = new int[m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(matrix[i][j] == 0) {
row[i] = 1;
col[j] = 1;
}
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(row[i] == 1 || col[j] == 1) {
matrix[i][j] = 0;
}
}
}
}
}