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(m + n) 额外空间。
- 将矩阵中所有 0 元素的所在行,列记录下来。
- 将记录下来的行号,整行设为0,将记录下来的列号,整列设为0.
void setZeroes(vector<vector<int>>& matrix) { unordered_set<int> seti;
unordered_set<int> setk; for (int i = ; i < matrix.size(); i++) {
for (int k = ; k < matrix[].size(); k++) {
if (matrix[i][k] == ) {
seti.insert(i);
setk.insert(k);
}
}
} unordered_set<int>::iterator s_iter;
for (s_iter = seti.begin(); s_iter != seti.end(); s_iter++) {
for (int k = ; k < matrix[].size(); k++) {
matrix[*s_iter][k] = ;
}
} for (s_iter = setk.begin(); s_iter != setk.end(); s_iter++) {
for (int i = ; i < matrix.size(); i++) {
matrix[i][*s_iter] = ;
}
}
}