[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。
思路: 想了很久都沒想到O(1)空間複雜度,太蠢了,就先用O(m+n)的空間複雜度硬爆先吧。
用兩個數組分別記錄爲0的行和列的下標,然後最後遍歷的時候設0。
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int leni = matrix.size();
if (leni == 0) {
return;
}
vector<int> is0i;
vector<int> is0j;
int lenj = matrix[0].size();
for (int i=0; i<leni; ++i) {
for (int j=0; j<lenj; ++j) {
if (matrix[i][j] == 0) {
is0i.push_back(i);
is0j.push_back(j);
}
}
}
for (int i=0; i<is0i.size(); ++i) {
for (int j=0; j<lenj; ++j) {
matrix[is0i[i]][j] = 0;
}
}
for (int j=0; j<is0j.size(); ++j) {
for (int i=0; i<leni; ++i) {
matrix[i][is0j[j]] = 0;
}
}
}
};
然後去Discuss學習了一波,人家把記錄這些信息的都放在matrix的第一行和第一列,然後用兩個boolean值來特別處理第一行和第一列即可。