zoukankan      html  css  js  c++  java
  • 73. Set Matrix Zeroes

    Problem:

    Given a (m imes 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?

    思路
    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

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    测网速
    fseek 在以字符串模式打开的文件中工作不正常 [MSDN]
    Inno Setup: Ask for reboot after uninstall
    【Inno Setup】Pascal 脚本 ---- 事件函数
    在安装程序之前,预先安装别的程序
    【Inno Setup】查看是否安装了VC++ 2015 Redistributeable
    spark学习笔记
    docker学习笔记2
    kafka读书笔记《kafka权威指南》2018
    mongodb
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12247525.html
Copyright © 2011-2022 走看看