[LeetCode] 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?

分别记录两个向量x, y,保存行和列是否有0,再次遍历数组时查询对应的行和列然后修改值。
 1 class Solution {
 2 private:
 3     bool x[1000];
 4     bool y[1000];
 5 public:
 6     void setZeroes(vector<vector<int> > &matrix) {
 7         // Start typing your C/C++ solution below
 8         // DO NOT write int main() function
 9         memset(x, false, sizeof(x));
10         memset(y, false, sizeof(y));
11         
12         for(int i = 0; i < matrix.size(); i++)
13             for(int j = 0; j < matrix[i].size(); j++)
14                 if (matrix[i][j] == 0)
15                 {
16                     x[i] = true;
17                     y[j] = true;
18                 }
19                 
20         for(int i = 0; i < matrix.size(); i++)
21             for(int j = 0; j < matrix[i].size(); j++)
22                 if (x[i] || y[j])
23                     matrix[i][j] = 0;
24     }
25 };
原文地址:https://www.cnblogs.com/chkkch/p/2775662.html