`

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.

给定一个m * n的矩阵,如果一个元素为0,那么把这个元素所在的行和列都设置为0。我们可以借助两个boolean数组,一个代表行row,一个代表列col。遍历数组,如果遇到元素matrix[i][j]为0,就把相应的行row[i]设置为true; 相应的列col[j]设置为true。最后遍历这两个boolean数组,当遇到true时(row[i] == true || col[j] == true)就把当前元素设置为0。空间复杂度为O(m+n)。代码如下:
public class Solution {
    public void setZeroes(int[][] matrix) {
        if(matrix == null || matrix.length == 0)
            return;
        int m = matrix.length;
        int n = matrix[0].length;
        boolean[] row = new boolean[m];
        boolean[] col = new boolean[n];
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++) {
                if(matrix[i][j] == 0) {
                    row[i] = true;
                    col[j] = true;
                }
            }
            
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++) {
                if(row[i] == true || col[j] == true) 
                    matrix[i][j] = 0;
            }
    }
}


还有一种优化的方法可以把空间复杂度优化为O(1), 代码如下:
public class Solution {
    public void setZeroes(int[][] matrix) {
        if(matrix == null || matrix.length == 0) return;
        int m = matrix.length;
        int n = matrix[0].length;
        boolean row = false, col = false;
        for(int i = 0; i < m; i++)  
            for(int j = 0; j < n; j++) {
                if(matrix[i][j] == 0) {
                    if(i == 0) {
                        row = true;
                    } else if(j == 0){
                        col = true;
                    } else {
                        matrix[i][0] = 0;
                        matrix[0][j] = 0;
                    }
                }
            }
        for(int i = m - 1; i >= 0; i--)
            for(int j = n - 1; j >= 0; j--) {
                if(i == 0 && row == true || j == 0 && col == true || matrix[i][0] == 0 || matrix[0][j] == 0)
                    matrix[i][j] = 0;
            }
    }
}

0
6
分享到:
评论

相关推荐

    javalruleetcode-SDE-Problems:标准SDE问题列表

    Zeros Pascal Triangle Next Permutation Inversion of Array (Using Merge Sort) Stock Buy and Sell Rotate Matrix 第3天:(数学) Excel 列号 在 log N 中查找 n^x 在数字的阶乘中计算尾随零 在 Log N 网格中...

    Zeros2.2.3 初步体验

    试用Zeros2.2.3 博文链接:https://corelengine.iteye.com/blog/230268

    前端开源库-count-trailing-zeros

    前端开源库-count-trailing-zeros计数尾随零,计数二进制整数的尾随零的数目。

    zeros-ice-3.6.2-cp27-amd64.whl

    ice中间件,可以用来开发,eclipse开发集成环境中可以

    ndarray-matrix-vector-multiply:密集矩阵向量乘法

    例子 var mvp = require ( "ndarray-matrix-vector-product" )var zeros = require ( "zeros" )//Initialize some vectors and a matrixvar x = zeros ( [ 16 ] )var M = zeros ( [ 16 , 8 ] )var y = zeros ( [ 8 ]...

    ZerOS

    ZerOS-bmp存放一些图片-boot系统启动所需的各种固件和配置-docs文档-外部外部依赖库,如csud usb控制模块-包括头文件-src源文件-对象生产的OBJ文件-kernel.disasm对应的汇编-kernel.elf生成的elf文件-kernel.img ...

    Zeros and zero dynamics Ch4.pdf

    Zeros and zero dynamics Ch4.pdf

    python中numpy.zeros(np.zeros)的使用方法

    用法:zeros(shape, dtype=float, order=’C’) 返回:返回来一个给定形状和类型的用0填充的数组; 参数:shape:形状 dtype:数据类型,可选参数,默认numpy.float64 dtype类型: t ,位域,如t4代表4位 b,布尔值,true...

    HJ Ryser __Combinatorl propertiesof matricesof zeros and ones.pdf

    HJ Ryser __Combinatorl propertiesof matricesof zeros and ones.pdfHJ Ryser __Combinatorl propertiesof matricesof zeros and ones.pdf

    基于dijkstra的低耗路由matlab仿真

    Inputs: [AorV] Either A or V where A is a NxN adjacency matrix, where A(I,J) is nonzero if and only if an ... I have solved this issue by using NaNs in the table rather than a sparse matrix of zeros.

    zeros

    Because there is 2 *tail* zeros in number 3628800重要的! 不要尝试计算阶乘! 首先-您将无法获得大数字的确切答案。 第二-计算大整数可能需要花费数年的时间! 尝试不用这种计算就可以考虑出您的出色解决方案。...

    f1zeros(size(f0)).pdf

    f1zeros(size(f0)).pdf

    matrix-go:在Golang中实现的用于矩阵处理的实验库

    // Create a 2 x 3 matrix. m := dense . New ( 2 , 3 )( 0 , 1 , 2 , 3 , 4 , 5 , ) 要创建零矩阵,请调用dense.Zeros 。 // Create a 2 x 3 zero matrix. m := dense . Zeros ( 2 , 3 ) 运作方式 加减法 用...

    Farrow结构下的时间同步模块的MATLAB仿真源码

    N = 23; % filter order, odd better ... % impulse response coefficient matrix magresp = zeros(Nfil,Npt); phasdel = zeros(Nfil,Npt-1); xvec=zeros(Nfil,1); % fractional delay vector P = 2; % po

    new_zeros() pytorch版本的转换方式

    logprobs.new_zeros(logprobs.size()) pytorch 0.4版本中用到的 新建一个与logprobs类型相同的Variable 转换为pytorch0.2等版本 logprobs.new(logprobs.size()).zero_() 以上这篇new_zeros() pytorch版本的转换...

    zeros:对OS开发人员进行另一次破解。

    ZerOS的 目标 该项目的目标是创建一个在完全模块化内核上运行的OS。 除了必要的系统设置外,所有内容都将作为模块加载。 内核本身没有其他内置功能。

    leading-zeros:在整数前加上前导零

    $ npm install --save leading-zeros 用法 var leadingZeros = require ( 'leading-zeros' ) ; // arguments -&gt; (number, amount of zero to be prepended) leadingZeros ( 48 , 5 ) ; // =&gt; '0000048' ...

    zeros:用零初始化 ndarray

    ndarray.zeros的替代ndarray.zeros (在 1.0.0 中已删除) 例子 var zeros = require ( "zeros" ) //Creates a 64x64 ndarray over a float64array filled with 0 var x = zeros ( [ 64 , 64 ] ) 它还接受文档中...

Global site tag (gtag.js) - Google Analytics