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

运行结果

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

相关推荐
zaiyang遇见15 分钟前
【递归完全搜索】CCC 2008 - 24点游戏Twenty-four
算法·游戏·c/c++·全排列·信息学奥赛
Mr_Xuhhh21 分钟前
传输层协议 TCP(1)
运维·服务器·网络·c++·网络协议·tcp/ip·https
Python智慧行囊21 分钟前
排序算法总结
数据结构·算法
似水流年流不尽思念25 分钟前
常见的排序算法有哪些?它们的平均时间复杂度是多少?
后端·算法
sTone873751 小时前
QuickJS 的核心概念和核心 API
前端·c++
楽码1 小时前
端到端应用Hmac加密
服务器·后端·算法
草莓熊Lotso1 小时前
《吃透 C++ 类和对象(中):拷贝构造函数与赋值运算符重载深度解析》
开发语言·c++·经验分享·笔记·其他
楚Y6同学2 小时前
QT之键盘控制虚拟遥控系统开发总结
开发语言·c++·qt·串口通信
Morriser莫2 小时前
图论Day2学习心得
算法·图论
zyd09152 小时前
代码随想录Day50:图论(图论理论、深度搜索理论、所有可达路径、广度搜索理论)
java·数据结构·算法·leetcode·图论