Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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?
思路分析:这题主要考如何复用空间以便节省space。容易想到的思路是,先扫描数组,保存下所有应该赋值为0的行和列的index,然后再进行矩阵赋值操作,但是需要O(m+n)额外空间。如何才能使用constant space解决本题呢?这里要体会一个思想,就是最小化空间使用的原则是只保存真正需要保存的值,如果一个位置的最终值已经确定,那么这一个位置在算法运行中就可以填入任何值,达到空间复用的目的。具体而言,我们可以先扫描数组,找到第一个0,记下这个0的rowIndex和colndex,显然这个0对应的行和列最终肯定都是0,因此我们可以利用这个行和列作为标记数组,去记录其他行和列是否应该赋值成0。所以我们再扫描一遍数组,通过标记行和列(rowIndex和colndex对应的行与列)进行标记,然后根据标记进行赋值0操作,最后把标记行和列赋值为0即可。所以,这题可以学到的是,当我们已经确定某一些空间的最终输出的时候,我们就可以复用这些空间,比如拿来做标记数组,而不必开辟额外空间,达到节省空间的目的。当然这样做也是以牺牲时间为代价的(做更多次的数组扫描)。
AC Code:
public class Solution {
public void setZeroes(int[][] matrix) {
//0527
int m = matrix.length;
if(m == 0) return;
int n = matrix[0].length;
if(n == 0) return;
//find a zero element
int zeroLabelRowIndex = -1;
int zeroLabelColIndex = -1;
boolean found = false;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(matrix[i][j] == 0){
zeroLabelRowIndex = i;
zeroLabelColIndex = j;
found = true;
break;
}
}
if(found) break;
}
if(!found) return;
for(int i = 0; i < m; i++){
if(i == zeroLabelRowIndex) continue;
for(int j = 0; j < n; j++){
if(j == zeroLabelColIndex) continue;
if(matrix[i][j] == 0){
matrix[i][zeroLabelColIndex] = 0;
matrix[zeroLabelRowIndex][j] = 0;
}
}
}
for(int i = 0; i < m; i++){
if(i == zeroLabelRowIndex) continue;
if(matrix[i][zeroLabelColIndex] == 0){
for(int j = 0; j < n; j++){
matrix[i][j] = 0;
}
}
}
for(int j = 0; j < n; j++){
if(j == zeroLabelColIndex) continue;
if(matrix[zeroLabelRowIndex][j] == 0){
for(int i = 0; i < m; i++){
matrix[i][j] = 0;
}
}
}
for(int i = 0; i < m; i++){
matrix[i][zeroLabelColIndex] = 0;
}
for(int j = 0; j < n; j++){
matrix[zeroLabelRowIndex][j] = 0;
}
//0540
}
}