自学内容网 自学内容网

73. 矩阵置零

  1. https://leetcode.cn/problems/set-matrix-zeroes/

  2. 在原表上做修改,需要记录哪一行那一列是0,所以不是发现为0后原地修改。

  3. 使用row和col(Set集合)记录为0的行列,然后逐一更新matrixs即可。

  4. 时间复杂度O(nm),空间复杂度O(n + m)

class Solution {
    public void setZeroes(int[][] matrix) {
        List<Integer> row = new ArrayList<>();
        List<Integer> col = new ArrayList<>();
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] == 0) {
                    row.add(i);
                    col.add(j);
                }
            }
        }
        for (int i = 0; i < row.size(); i++) {
            Arrays.fill(matrix[row.get(i)], 0);
        }
        for (int i = 0; i < col.size(); i++) {
            for (int j = 0; j < matrix.length; j++) {
                matrix[j][col.get(i)] = 0;
            }
        }
    }
}```


原文地址:https://blog.csdn.net/Cw_Herry/article/details/142927615

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!