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),但是没有另外开辟空间,将标记记录在矩阵首行首列。增加判断首行首列是否要置0即可。
class Solution { public: void setZeroes(vector<vector<int> > &matrix) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int m=matrix.size(); int n=matrix[0].size(); int i,j; bool flag1=false;//第一列是否有0 bool flag2=false;//第二列是否有0 for(i=0;i<m;i++) { if(matrix[i][0]==0) { flag1=true; break; } } for(i=0;i<n;i++) { if(matrix[0][i]==0) { flag2=true; break; } } //若此数为0,则行首列首置0 for(i=1;i<m;i++) { for(j=1;j<n;j++) { if(matrix[i][j]==0) { matrix[i][0]=0; matrix[0][j]=0; } } } //列行中有0,则此数置0 for(i=1;i<m;i++) { for(j=1;j<n;j++) { if(matrix[i][0]==0||matrix[0][j]==0) matrix[i][j]=0; } } //判断首行首列是否需要置0 if(flag1) { for(i=0;i<m;i++) matrix[i][0]=0; } if(flag2) { for(j=0;j<n;j++) matrix[0][j]=0; } } };