首页 > 其他 > 详细

19.2.13 [LeetCode 73] Set Matrix Zeroes

时间:2019-02-13 20:19:21      阅读:139      评论: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.

Example 1:

Input: 
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
Output: 
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]

Example 2:

Input: 
[
  [0,1,2,0],
  [3,4,5,2],
  [1,3,1,5]
]
Output: 
[
  [0,0,0,0],
  [0,4,5,0],
  [0,3,1,0]
]

Follow up:

  • 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

题解

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

我一开始都没get到点在哪,试错之后才发现难点在哪……稍微用俩bool对 matrix[0][0] 的特殊情况处理一下就可以了

19.2.13 [LeetCode 73] Set Matrix Zeroes

原文:https://www.cnblogs.com/yalphait/p/10371671.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!