题目
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?
0 0 0 0
0 0 0 0
1 0 1 0
b = does first column have zero? = no
0 0 0 0
0 0 0 0
1 0 1 0
答案
O(mn) space
给定matrix A, 拷贝一个新的matrix B.
如果B[i][j] = 0, 则把A的第i行和第j列填0
O(m+n) space
if A[i][j] = 0, then list1.add(i), list2.add(j)
然后把list1里的行和list2里的列清0
O(1) (太长,以后缩减一下)
class Solution {
public void setZeroes(int[][] matrix) {
// Does first row, column have zeroes?
int m = matrix.length, n = matrix[0].length;
boolean first_row = false;
boolean first_col = false;
for(int i = 0; i < m; i++) {
if(matrix[i][0] == 0) {
first_col = true;
break;
}
}
for(int j = 0; j < n; j++) {
if(matrix[0][j] == 0) {
first_row = true;
break;
}
}
for(int i = 1; i < m; i++) {
for(int j = 1; j < n; j++) {
if(matrix[i][j] == 0) {
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for(int i = 1; i < m; i++) {
if(matrix[i][0] == 0) {
// Set this row to 0
for(int j = 1; j < n; j++) matrix[i][j] = 0;
}
}
for(int j = 1; j < n; j++) {
if(matrix[0][j] == 0) {
// Set this col to 0
for(int i = 1; i < m; i++) matrix[i][j] = 0;
}
}
if(first_row)
for(int j = 0; j < n; j++) matrix[0][j] = 0;
if(first_col)
for(int i = 0; i < m; i++) matrix[i][0] = 0;
}
}
