题目:
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:
解决方法一: O(m+n) space
Runtime:
4 ms
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?
public class Solution {
public void setZeroes(int[][] matrix) {
if(null==matrix||matrix.length<=0) return;
int row[] = new int[matrix.length];
int column[]= new int[matrix[0].length];
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[i].length;j++){
if(matrix[i][j]==0){
row[i]=1;
column[j]=1;
}
}
}
for(int i=0;i<matrix.length*matrix[0].length;i++){
int x=i/matrix[0].length;
int y=i%matrix[0].length;
if(row[x]==1) matrix[x][y]=0;
if(column[y]==1) matrix[x][y]=0;
}
}
}
解决方法二:常量空间复杂度 Runtime: 2 ms
public class Solution {
public void setZeroes(int[][] matrix) {
if(null==matrix||matrix.length<=0) return;
int m=matrix.length;
int n=matrix[0].length;
boolean row =false, column=false;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(matrix[i][j]==0){
if(i==0) row=true;
if(j==0) column=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(row)
for(int i=0;i<n;i++){
matrix[0][i]=0;
}
if(column)
for(int i=0;i<m;i++){
matrix[i][0]=0;
}
}
}
参考: