LeetCode/solutions/73. Set Matrix Zeroes.md
2019-02-21 19:06:48 +08:00

34 lines
1.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [73. Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/)
# 思路
题目要求将一个矩阵中元素0所在的行和列全部设置为0要求空间复杂度为O(1)。
如果不要求空间复杂度的话这题就简单了。先遍历一遍矩阵同时用一个数组或其他容器记录所有0的位置然后再将这些位置对应的行列都设置成0即可。
但是此方法额外开了一个数组,空间复杂度达不到要求。有没有什么方法能在不开数组的情况下也能记录这些位置呢?
答案是可以的。因为我们只需要记录哪些行、列需要被设置成全0即可而不需要记录所有0元素的位置。我们可以用第0行标记哪些列需要设置为全0用第0列标记哪些行需要设置为全0
由于第0行和第0列有重叠元素matrix[0][0]所以我们还需要开一个额外的变量来记录第0列或行是否需要设置为0。
时间复杂度O(mn), 空间复杂度O(1)
# C++
``` C++
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int col0 = 1, r = matrix.size(), c = matrix[0].size();
for(int i = 0; i < r; i++){ // 记录哪些行列需要设置为全0
if(matrix[i][0] == 0) col0 = 0;
for(int j = 1; j < c; j++)
if(matrix[i][j] == 0)
matrix[i][0] = matrix[0][j] = 0;
}
for(int i = 1; i < r; i++){
for(int j = 1; j < c; j++)
if(matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
}
if(matrix[0][0] == 0) // 处理第0行
for(int i = 0; i < c; i++) matrix[0][i] = 0;
if(col0 == 0) // 处理第0列
for(int i = 0; i < r; i++) matrix[i][0] = 0;
}
};
```