LeetCode 73 Set Matrix Zeroes
2016-08-19 本文已影响18人
ShuiLocked
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.
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?
一开始想到了空间O(m + n)的算法,用一个数组arr[m+n]记录某行或者某列是否需要设为0,遍历一遍数组,若num[i][j]==0,则对应的赋值arr[i]=0,arr[m+j]=0即可。
没想到constant的方法,上网搜一番之后发现:
没有必要新开一个arr[m+n]数组,其实遍历num[i][j]==0后,直接将num[i][0]与num[0][j]设为0即可~~确实啊!!!
不过对于首行和首列,这样直接改变它们的值会影响它们原本的值,而首行与首列是否set为0又是由它们原本的值决定的,因此一开始先扫一遍首行与首列,确定它们是否需要set,再扫描i=[2...m]与j=[2...n],判断其他行与列。
代码:
public void setZeroes(int[][] matrix) {
if (matrix.length == 0) return;
int m = matrix.length, n = matrix[0].length;
boolean row = false, col = false;
// Check first row & col
if (matrix[0][0] == 0) {
row = true;
col = true;
} else {
for (int i = 1; i < m; i++) {
if (matrix[i][0] == 0) {
col = true;
matrix[0][0] = 0;
break;
}
}
for (int j = 1; j < n; j++) {
if (matrix[0][j] == 0) {
row = true;
matrix[0][0] = 0;
break;
}
}
}
// Check other rows & cols
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;
}
}
}
// Assign rows
for (int i = 1; i < m; i++) {
if (matrix[i][0] == 0) {
for (int j = 1; j < n; j++) matrix[i][j] = 0;
}
}
// Assign cols
for (int j = 1; j < n; j++) {
if (matrix[0][j] == 0) {
for (int i = 1; i < m; i++) matrix[i][j] = 0;
}
}
// Assign first row & col
if (col) {
for (int i = 1; i < m; i++) matrix[i][0] = 0;
}
if (row) {
for (int j = 1; j < n; j++) matrix[0][j] = 0;
}
}