标签:style blog http color io ar for strong sp
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?
1 class Solution { 2 public: 3 void setZeroes(vector<vector<int> > &matrix) { 4 for(int i=0; i<matrix.size(); ++i) //将0元素所在行和列的非0元素置为INF 5 for(int j=0; j<matrix[i].size(); ++j) 6 if( !matrix[i][j] ) setINF(matrix, i, j); 7 for(int i=0; i<matrix.size(); ++i) //将所有INF元素置为0 8 for(int j=0; j<matrix[i].size(); ++j) 9 if( matrix[i][j] == INF ) matrix[i][j] = 0; 10 } 11 12 void setINF(vector<vector<int> > &matrix, int x, int y) { 13 for(int i=0; i<matrix.size(); ++i) 14 if( matrix[i][y] ) matrix[i][y] = INF; 15 for(int i=0; i<matrix[x].size(); ++i) 16 if( matrix[x][i] ) matrix[x][i] = INF; 17 } 18 19 private: 20 static const int INF = 0x3fffffff; 21 };
方法二:利用第一行和第一列标记哪行和哪列全部置0,需要注意,第一行和第一列需要额外标记
1 class Solution { 2 public: 3 void setZeroes(vector<vector<int> > &matrix) { 4 bool frow = false, fcol = false; 5 for(int i=0; i<matrix[0].size(); ++i) //判断第一行是否需要清0 6 if( !matrix[0][i] ) { 7 frow = true; 8 break; 9 } 10 for(int i=0; i<matrix.size(); ++i) //判断第一列是否需要清0 11 if( !matrix[i][0] ) { 12 fcol = true; 13 break; 14 } 15 for(int i=1; i<matrix.size(); ++i) 16 for(int j=1; j<matrix[i].size(); ++j) 17 if( !matrix[i][j] ) { //当前元素所在行和所在列,第一行和第一列对应的元素置0,作为标记 18 matrix[i][0] = matrix[0][j] = 0; 19 } 20 for(int i=1; i<matrix.size(); ++i) 21 for(int j=1; j<matrix[i].size(); ++j) 22 if( !matrix[i][0] || !matrix[0][j] ) matrix[i][j] = 0; //按照标记来给对应的行和列置0 23 if( frow ) 24 for(int i=0; i<matrix[0].size(); ++i) matrix[0][i] = 0; 25 if( fcol ) 26 for(int i=0; i<matrix.size(); ++i) matrix[i][0] = 0; 27 } 28 };
标签:style blog http color io ar for strong sp
原文地址:http://www.cnblogs.com/bugfly/p/4009079.html