码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Solution-73

时间:2020-02-01 10:24:53      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:自底向上   --   idea   could   etc   column   leetcode   tor   pac   

73. Set Matrix Zeroes

Given a \(m \times 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:
\(\bullet\)A straight forward solution using O(mn) space is probably a bad idea.
\(\bullet\)A simple improvement uses O(m + n) space, but still not the best solution.
\(\bullet\)Could you devise a constant space solution?

思路:
1.若某一个数为0,则将这一行的第一个数以及这一列的第一个数设为0作为标记位。值得注意的是,如果第一列某个数为0,则这一行和第一列的数都要变为0,所以要单独设置一个标志位col0。
2.检查行时自底向上,检查列时自右向左。注意检查列时只能检查到第二列,否则会重复变0。最后检查col0是否为0,若为0,则将第一列变为0。

Solution:

void setZeroes(vector<vector<int>>& matrix) {
    int col0 = 1, rows = matrix.size(), cols = matrix[0].size();
        
    for (int i = 0; i < rows; i++) {
        if (matrix[i][0] == 0) col0 = 0;
        for (int j = 1; j < cols; j++) {
            if (matrix[i][j] == 0 )    
                matrix[i][0] = matrix[0][j] = 0;
        }
    }

    for (int i = rows-1; i >= 0; i--) {
        for (int j = cols-1; j >= 1; j--) {
            if (matrix[i][0] == 0 || matrix[0][j] == 0)
                matrix[i][j] = 0;
        }
    }
        
    if (col0 == 0) {
        for (int i = 0; i < rows; i++) {
            matrix[i][0] = 0;
        }
    } 
}

性能:
Runtime: 44 ms??Memory Usage: 11.5 MB

LeetCode Solution-73

标签:自底向上   --   idea   could   etc   column   leetcode   tor   pac   

原文地址:https://www.cnblogs.com/dysjtu1995/p/12247525.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!