【LeetCode】73. 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?
提示:
这题要求用常数的空间去解决,那么我们就可以利用第一行和第一列的元素去标记该行或该列是否在更新时要全部变成0。但是单纯这样操作会使得第一行和第一列的原始状态丢失。
因此,我们需要额外一个变量去保存第一列(或者第一行也可以)在更新时是否要变成0,这样就不会有问题了。
另外还有一个让代码更加精简的小窍门,就是在更新的时候从下往上(Bottom-Up),这样就不用担心会破坏第一行或第一列的数据了。
代码:
class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int height = matrix.size(); int width = height ? matrix[0].size() : 0; if (!height || !width) { return; } int col0 = 1; for (int i = 0; i < height; ++i) { if (matrix[i][0] == 0) { col0 = 0; } for (int j = 1; j < width; ++j) { if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } for (int i = height - 1; i >= 0; --i) { for (int j = width - 1; j >= 1; --j) { if (matrix[i][0] == 0 || matrix[0][j] == 0) { matrix[i][j] = 0; } } if (col0 == 0) { matrix[i][0] = 0; } } } };