标签:tor return log simple ide color blog constant dev
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(m n) 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?
1 class Solution { 2 public: 3 void setZeroes(vector<vector<int> > &matrix) 4 { 5 int row=matrix.size(); 6 int col=matrix[0].size(); 7 8 if(row==0||col==0) return; 9 10 bool rFlag=false,cFlag=false; 11 for(int i=0;i<row;++i) 12 { 13 if(matrix[i][0]==0) 14 { 15 rFlag=true; 16 break; 17 } 18 } 19 for(int i=0;i<col;++i) 20 { 21 if(matrix[0][i]==0) 22 { 23 cFlag=true; 24 break; 25 } 26 } 27 28 for(int i=1;i<row;++i) 29 { 30 for(int j=1;j<col;++j) 31 { 32 if(matrix[i][j]==0) 33 { 34 matrix[i][0]=0; 35 matrix[0][j]=0; 36 } 37 } 38 } 39 40 for(int i=1;i<row;++i) 41 { 42 for(int j=1;j<col;++j) 43 { 44 if(matrix[i][0]==0||matrix[0][j]==0) 45 matrix[i][j]=0; 46 } 47 } 48 49 if(rFlag) 50 { 51 for(int i=0;i<row;++i) 52 matrix[i][0]=0; 53 } 54 if(cFlag) 55 { 56 for(int i=0;i<col;++i) 57 matrix[0][i]=0; 58 } 59 60 } 61 };
代码参考了Gradyang的博客
[Leetcode] set matrix zeroes 矩阵置零
标签:tor return log simple ide color blog constant dev
原文地址:http://www.cnblogs.com/love-yh/p/7136958.html