Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
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?
Have you met this question in a real interview?
思路 : space O(m + n)解法, 设置俩数组 来存储 row 和 column , 遇到matrix[i][j] == 0 就把 row[i] = true; column[j] = true;
space O(1) 解法, 就是把 第一行 和 第一列当做一个 buffer 来存储 row 和 column
易错点: 最后 改成 0 的时候 ,一定要把 第一行 和 第一列 和 其他的分开来。 先 1 - m , 1 - n , 最后再 0行 0 列。
public class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean[] row = new boolean[m];
boolean[] column = 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;
column[j] = true;
}
}
}
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(row[i] || column[j])
matrix[i][j] = 0;
}
}
}
}
public class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean isRow0 = false, isColumn0 = false;
for(int i = 0; i < m; i++){
if(matrix[i][0] == 0){
isColumn0 = true;
break;
}
}
for(int i = 0; i < n; i++){
if(matrix[0][i] == 0){
isRow0 = true;
break;
}
}
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 i = 1; i < m; i++){//------
for(int j = 1; j < n; j++){//-------
if(matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
}
}
if(isColumn0){
for(int i = 0; i < m; i++)
matrix[i][0] = 0;
}
if(isRow0){
for(int i = 0; i < n; i++)
matrix[0][i] = 0;
}
}
}