题目链接:https://leetcode.com/problems/set-matrix-zeroes/
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
click to show 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)的时间复杂度比较容易做。
代码如下:
class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int m=matrix.size(), n=matrix[0].size(), flagRow[m], flagCol[n]; memset(flagRow, 1, sizeof(flagRow)); memset(flagCol, 1, sizeof(flagCol)); for(int i = 0; i< m; i++)//标记 for(int j =0; j< n; j++) { if(flagRow[i] == 0 && flagCol[j] == 0) continue; if(matrix[i][j] == 0) { flagRow[i] = 0; flagCol[j] = 0; } } for(int i = 0; i< m; i++)//设置每一行的0 { if(flagRow[i] == 0) for(int j =0; j< n; j++) matrix[i][j] = 0; } for(int i = 0; i< n; i++)//设置每一列的0 { if(flagCol[i] == 0) for(int j = 0; j < m; j++) matrix[j][i] = 0; } } };
代码如下:
class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int flagRow=false, flagCol=false,m=matrix.size(), n=matrix[0].size(); for(int i =0; i < m; i++)//判断第一列是否应该全为0 flagCol = (matrix[i][0]==0)?true:flagCol; for(int i =0; i < n; i++)//判断第一列是否应该全为0 flagRow = (matrix[0][i]==0)?true:flagRow; for(int i =1; i< m; i++) for(int j =1; j< n; j++) { matrix[i][0] = (matrix[i][j]==0)?0:matrix[i][0];//当前元素为0,则当前行首为0 matrix[0][j] = (matrix[i][j]==0)?0:matrix[0][j];//当前元素为0,则当前列首为0 } for(int i = 1; i < m; i++) for(int j =1; j< n; j++) if(!matrix[i][0] || !matrix[0][j])//如果行列标记为0,则设置为0 matrix[i][j] = 0; if(flagCol)//如果第一列应该设置为0 for(int i =0; i< m; i++) matrix[i][0] = 0; if(flagRow)//如果第一行应该设置为0 for(int i = 0; i< n; i++) matrix[0][i] = 0; } };第二种方法参照:http://fisherlei.blogspot.com/2013/01/leetcode-set-matrix-zeroes.html