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.
1 void setZeroes(vector<vector<int>>& matrix) { 2 3 unordered_set<int> seti; 4 unordered_set<int> setk; 5 6 for (int i = 0 ; i < matrix.size(); i++) { 7 for (int k = 0 ; k < matrix[0].size(); k++) { 8 if (matrix[i][k] == 0) { 9 seti.insert(i); 10 setk.insert(k); 11 } 12 } 13 } 14 15 unordered_set<int>::iterator s_iter; 16 for (s_iter = seti.begin(); s_iter != seti.end(); s_iter++) { 17 for (int k = 0 ; k < matrix[0].size(); k++) { 18 matrix[*s_iter][k] = 0; 19 } 20 } 21 22 for (s_iter = setk.begin(); s_iter != setk.end(); s_iter++) { 23 for (int i = 0; i < matrix.size(); i++) { 24 matrix[i][*s_iter] = 0; 25 } 26 } 27 }
时间: 2024-10-22 09:26:50