set-matrix-zeroes当元素为0则设矩阵内行与列均为0

题目描述

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(m n) 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?

 1 class Solution {
 2 public:
 3     void setZeroes(vector<vector<int> > &matrix) {
 4         vector<bool> col,row;
 5         col.resize(matrix[0].size(), false);
 6         row.resize(matrix.size(), false);
 7         for (int i = 0; i < matrix.size(); ++i)
 8         {
 9             for (int j = 0; j < matrix[i].size();++j)
10             {
11                 if(matrix[i][j]==0)
12                 {
13                     col[j]=true;
14                     row[i]=true;
15                 }
16             }
17         }
18         for (int i = 0; i < matrix.size(); ++i)
19         {
20             for (int j = 0; j < matrix[i].size();++j)
21             {
22                 if(col[j]||row[i])
23                 {
24                     matrix[i][j]=0;
25                 }
26             }
27         }
28     }
29 };

最优解法:

首先判断第一行和第一列是否有元素为0,而后利用第一行和第一列保存状态,最后根据开始的判断决定是否将第一行和第一列置0

 1 //时间复杂度O(mn),空间复杂度O(1)
 2 //利用第一行和第一列的空间做记录
 3 class Solution {
 4 public:
 5     void setZeroes(vector<vector<int> > &matrix) {
 6         const int row = matrix.size();
 7         const int col = matrix[0].size();
 8         bool row_flg = false, col_flg = false;
 9          
10         //判断第一行和第一列是否有零,防止被覆盖
11         for (int i = 0; i < row; i++)
12             if (0 == matrix[i][0]) {
13                 col_flg = true;
14                 break;
15             }
16         for (int i = 0; i < col; i++)
17             if (0 == matrix[0][i]) {
18                 row_flg = true;
19                 break;
20             }
21         //遍历矩阵,用第一行和第一列记录0的位置
22         for (int i = 1; i < row; i++)
23             for (int j = 1; j < col; j++)
24                 if (0 == matrix[i][j]) {
25                     matrix[i][0] = 0;
26                     matrix[0][j] = 0;
27                 }
28         //根据记录清零
29         for (int i = 1; i < row; i++)
30             for (int j = 1; j < col; j++)
31                 if (0 == matrix[i][0] || 0 == matrix[0][j])
32                     matrix[i][j] = 0;
33         //最后处理第一行
34         if (row_flg)
35             for (int i = 0; i < col; i++)
36                 matrix[0][i] = 0;
37         if (col_flg)
38             for (int i = 0; i < row; i++)
39                 matrix[i][0] = 0;
40     }
41 };
原文地址:https://www.cnblogs.com/zl1991/p/9630343.html