Leetcode—73.矩阵置零【中等】

2023每日刷题(六十六)

Leetcode---73.矩阵置零

空间复杂度为O(m+n)版实现代码

cpp 复制代码
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int rowLen = matrix.size();
        int colLen = matrix[0].size();
        vector<int> row(rowLen, 0);
        vector<int> col(colLen, 0);
        for(int i = 0; i < rowLen; i++) {
            for(int j = 0; j < colLen; j++) {
                if(matrix[i][j] == 0) {
                    row[i] = 1;
                    col[j] = 1;
                }
            }
        }
        for(int i = 0; i < rowLen; i++) {
            for(int j = 0; j < colLen; j++) {
                if(row[i] || col[j]) {
                    matrix[i][j] = 0;
                }
            }
        }
    }
};

运行结果

优化空间复杂度为O(1)版算法思想

优化版实现代码

cpp 复制代码
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        bool rowFlag = false, colFlag = false;
        int rowLen = matrix.size();
        int colLen = matrix[0].size();
        for(int i = 0; i < rowLen; i++) {
            if(!matrix[i][0]) {
                colFlag = true;
            }
        }

        for(int j = 0; j < colLen; j++) {
            if(!matrix[0][j]) {
                rowFlag = true;
            }
        }

        for(int i = 1; i < rowLen; i++) {
            for(int j = 1; j < colLen; j++) {
                if(!matrix[i][j]) {
                    matrix[i][0] = matrix[0][j] = 0;
                }
            }
        }

        for(int i = 1; i < rowLen; i++) {
            for(int j = 1; j < colLen; j++) {
                if(!matrix[i][0] || !matrix[0][j]) {
                    matrix[i][j] = 0;
                }
            }
        }

        if(colFlag) {
            for(int i = 0; i < rowLen; i++) {
                matrix[i][0] = 0;
            }
        }

        if(rowFlag) {
            for(int j = 0; j < colLen; j++) {
                matrix[0][j] = 0;
            }
        }
    }
};

运行结果

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
爬山算法3 小时前
Netty(13)Netty中的事件和回调机制
java·前端·算法
CoovallyAIHub3 小时前
是什么支撑L3自动驾驶落地?读懂AI驾驶与碰撞预测
深度学习·算法·计算机视觉
玉树临风ives3 小时前
atcoder ABC436 题解
c++·算法·leetcode·atcoder·信息学奥赛
fpcc3 小时前
C++23中的自定义模块开发
c++·c++23
圣保罗的大教堂3 小时前
leetcode 2110. 股票平滑下跌阶段的数目 中等
leetcode
patrickpdx3 小时前
leetcode:相等的有理数
算法·leetcode·职场和发展
weixin_537217063 小时前
Ai算法资源合集
经验分享
dragoooon343 小时前
[C++——lesson29.数据结构进阶——「AVL树」]
算法
碧海银沙音频科技研究院4 小时前
论文写作word插入公式显示灰色解决办法
人工智能·深度学习·算法
斌蔚司李4 小时前
机械革命 AX210 网卡断网断流、蓝牙断流问题解决办法
经验分享