leetcode : 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.
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?
要改完整个矩阵肯定要m*n的时间复杂度,那么可以大大方方的遍历好几次矩阵,反正时间复杂也还是m*n。数量级不会变
在可以随便遍历几次矩阵的基础上,再考虑优化算法的空间复杂度,比较容易想到的就是记录每个0点的下标i,j
用m+n的两个数组活着容器效率比较高。
更进一步按照题目优化,我们可以把存放m行跟n列是否应该为0的两个矩阵放到矩阵中,即第一行与第一列。但是需要有一些机制来区分第一行根第一列是否应该被全部初始化为0,可以用两个变量保存第一行第一列是否应该为0
AC代码:
class Solution { public: void setZeroes(vector<vector<int> > &matrix) { int col = matrix.size(),row = matrix[0].size(); bool colZero = false, rowZero = false; // 标记应该被set zero的行跟列 for(int i = 0; i < col; ++i){ for(int j = 0; j < row; ++j){ if(!colZero && i == 0 && matrix[i][j] == 0) colZero = true; if(!rowZero && j == 0 && matrix[i][j] == 0) rowZero = true; if(matrix[i][j] == 0){ matrix[i][0] = 0; matrix[0][j] = 0; } } } //开始置0 for(int i = 1; i < col; ++i){ for(int j = 1; j < row; ++j){ if(!matrix[i][0] || !matrix[0][j]) matrix[i][j] = 0; } } if(colZero){ for(int i = 0; i < row; ++i) matrix[0][i] = 0; } if(rowZero){ for(int i = 0; i < col; ++i) matrix[i][0] = 0; } } };
浙公网安备 33010602011771号