【矩阵】73. 矩阵置零

题目

法1:自己想的笨蛋方法

java 复制代码
class Solution {
    public void setZeroes(int[][] matrix) {
        Set<Integer> rowSet = new HashSet<>();
        Set<Integer> columnSet = new HashSet<>();
        for (int i = 0; i < matrix.length; ++i) {
            for (int j = 0; j < matrix[0].length; ++j) {
                if (matrix[i][j] == 0) {
                    rowSet.add(i);
                    columnSet.add(j);
                }
            }
        }
        for (int i = 0; i < matrix.length; ++i) {
            if (rowSet.contains(i)) {
                Arrays.fill(matrix[i], 0);
            }
        }
        for (int j = 0; j < matrix[0].length; ++j) {
            if (columnSet.contains(j)) {
                for (int i = 0; i < matrix.length; ++i) {
                    matrix[i][j] = 0;
                }
            }
        }
    }
}

// 代码优雅版
class Solution {
    public void setZeroes(int[][] matrix) {
        int m = matrix.length, 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] = col[j] = true;
                }
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (row[i] || col[j]) {
                    matrix[i][j] = 0;
                }
            }
        }
    }
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/set-matrix-zeroes/solutions/669901/ju-zhen-zhi-ling-by-leetcode-solution-9ll7/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

法2:

放个链接,估计真遇到了也写不出来。。。
https://leetcode.cn/problems/set-matrix-zeroes/solutions/670278/xiang-jie-fen-san-bu-de-o1-kong-jian-jie-dbxd/?envType=study-plan-v2&envId=top-100-liked

相关推荐
JianZhen✓6 小时前
电商 SKU 选择器:后端只给扁平列表,前端怎么反推规格矩阵并做到 O(1) 命中
前端·矩阵·状态模式
tellmewhoisi3 天前
深度学习0:数学知识:(雅可比矩阵)
人工智能·深度学习·矩阵
lisw059 天前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
DFT计算杂谈10 天前
可DIY布里渊区图像绘制编辑器
人工智能·机器学习·语言模型·矩阵·编辑器
Pniubi10 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵
Pniubi10 天前
力扣73 矩阵置零
算法·leetcode·矩阵
kingx311 天前
Bugku 逆向 MatrixHunter:黑盒 oracle + GF(2) 消元出唯一解
网络安全·矩阵·逆向·ctf
莱茶荼菜15 天前
【slam公式】
人工智能·线性代数·机器学习
吴名氏.15 天前
Java转AI Agent教程(第九周)错误矩阵
java·人工智能·矩阵·ai agent