力扣题解(73. 矩阵置零),带注释

题目描述

链接:点我

题解

java 复制代码
//法一  使用hashset记录有0的横纵坐标即可
class Solution {
    public void setZeroes(int[][] matrix) {
        HashSet<Integer> row = new HashSet<Integer>();
        HashSet<Integer> col = new HashSet<Integer>();
        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 < matrix.length;i++){
            for(int j = 0;j < matrix[i].length;j++){
                if(row.contains(i) || col.contains(j)){
                    matrix[i][j] = 0;
                }
            }
        }

    }
}

//法二,我也是看了题解才明白orz.......  此法的空间复杂度更小O(1)
class Solution {
    public void setZeroes(int[][] matrix) {
        int m = matrix.length , n = matrix[0].length;
        int flag = 0;  //标记第0列是否有0,有为1
        for(int i = 0;i < m;i++){
            if(matrix[i][0] == 0) flag = 1;
            for(int j = 1;j < n;j++){
                //通过其他列更新第0列,其他行更新第0行
                if(matrix[i][j] == 0) matrix[i][0] = matrix[0][j] = 0; 
            }
        }
        
        for(int i = m-1;i >= 0;i--){//防止每一列的第一个元素被提前更新,倒着遍历
            for(int j = 1;j < n;j++){ //注意这里是从1开始
                if(matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0;
            }
        }
        if(flag == 1){  //更新第0列
            for(int i =0;i < m; i++) matrix[i][0] = 0;
        }
    }
}
相关推荐
geovindu3 小时前
python:DecisionTree
开发语言·后端·python·算法
geovindu5 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
AllData公司负责人7 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
武子康8 小时前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习
夜不会漫长9 小时前
C++:C++11特性
开发语言·c++·算法
秋天的怀念_David9 小时前
算法一千零一夜 · 第三十七夜 · 类型的过路费
java·程序人生·算法
xckkcxxck12 小时前
Kaggle S6E10 冠军方案精读(二):245 个模型的合唱团,和一个只会“线性指挥“的老师
算法
饮水桶_T12 小时前
Git笔记
开发语言·笔记·算法
指掀涛澜天下惊13 小时前
强化学习进阶篇十四 DPO算法
深度学习·算法·机器学习·sft·预训练·dpo