您的位置:首页 > 其它

[LeetCode] Set Matrix Zeroes

2015-08-15 11:33 239 查看
This problem can be solved easily if we are allowed to use more than O(1) space. For example, you may create a copy of the original matrix (O(mn)-space) or just record the row and column indexes (O(m + n)-space). Well, is there a O(1)-space solution? Yes, you may refer to this link :-)

The key idea is to record the rows and columns that need to be set to zeroes directly in the matrix ( if (!matrix[i][j]) matrix[i][0] = matrix[0][j] = 0; ). The code is rewritten as follows.

class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
bool c0 = false;
for (int i = 0; i < m; i++) {
if (!matrix[i][0]) c0 = true;
for (int j = 1; j < n; j++)
if (!matrix[i][j]) matrix[i][0] = matrix[0][j] = 0;
}
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j; j--)
if (!matrix[i][0] || !matrix[0][j]) matrix[i][j] = 0;
if (c0) matrix[i][0] = 0;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: