[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.

click to show follow up.

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。

 1 class Solution {
 2 public:
 3     void setZeroes(vector<vector<int>>& matrix) {
 4         int rows = matrix.size();
 5         int cols = matrix[0].size();
 6         
 7         vector<bool> rowsVec(rows, false);
 8         vector<bool> colsVec(cols, false);
 9         
10         for (int i = 0; i < rows; ++i) {
11             for (int j = 0; j < cols; ++j) {
12                 if (matrix[i][j] == 0) {
13                     rowsVec[i] = true;
14                     colsVec[j] = true;
15                     continue;
16                 }
17             }
18         }
19         
20         for (int i = 0; i < rows; ++i) {
21             if (rowsVec[i]) {
22                 fill(&matrix[i][0], &matrix[i][0] + cols, 0);
23             }
24         }
25         
26         for (int j = 0; j < cols; ++j) {
27             if (colsVec[j]) {
28                 for (int i = 0; i < rows; ++i) {
29                     matrix[i][j] = 0;
30                 }
31             }
32         }
33     }
34 };
原文地址:https://www.cnblogs.com/skycore/p/4884001.html