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;
            }
        }
    }
};

运行结果

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

相关推荐
桦0几秒前
每天一道算法题【蓝桥杯】【山脉数组的峰顶索引】
c++·算法·leetcode·蓝桥杯
2301_800895101 分钟前
蓝桥杯好数
算法
S181517004864 分钟前
美发行业的数字化转型:从痛点出发,探索未来新机遇
大数据·人工智能·经验分享·笔记·科技
yngsqq1 小时前
贪心算法和遗传算法优劣对比——c#
算法·贪心算法·c#
onlyzzr1 小时前
Leetcode Hot100 第58题 23.合并K个升序链表
java·算法·leetcode
修己xj1 小时前
算法系列之回溯算法求解数独及所有可能解
算法
Foyo Designer1 小时前
【 <一> 炼丹初探:JavaWeb 的起源与基础】之 JavaWeb 项目的部署:从开发环境到生产环境
前端·经验分享·程序人生·firefox·学习方法·改行学it
axxy20001 小时前
C++ Primer Plus第十二章课后习题总结
c++
剑海风云2 小时前
73. 矩阵置零
java·数据结构·算法·矩阵
十年一梦实验室2 小时前
【C++】 嵌套类(Nested Class)
开发语言·c++