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

运行结果

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

相关推荐
愚润求学21 分钟前
【Linux】进程间通信(一):认识管道
linux·运维·服务器·开发语言·c++·笔记
珊瑚里的鱼36 分钟前
【滑动窗口】LeetCode 1658题解 | 将 x 减到 0 的最小操作数
开发语言·c++·笔记·算法·leetcode·stl
落樱弥城40 分钟前
角点特征:从传统算法到深度学习算法演进
人工智能·深度学习·算法
共享家95271 小时前
哈希的原理、实现
c++·算法
进击的小白菜1 小时前
用Java实现单词搜索(LeetCode 79)——回溯算法详解
java·算法·leetcode
珂朵莉MM2 小时前
2024 睿抗机器人开发者大赛CAIP-编程技能赛-专科组(国赛)解题报告 | 珂学家
开发语言·人工智能·算法·leetcode·职场和发展·深度优先·图论
小智学长 | 嵌入式2 小时前
进阶-数据结构部分:2、常用排序算法
java·数据结构·算法
少了一只鹅2 小时前
字符函数和字符串函数
c语言·算法
*才华有限公司*2 小时前
gRPC开发指南:Visual Studio 2022 + Vcpkg + Windows全流程配置
c++·ide·visual studio
Maplesoft2 小时前
精准掌控张力动态,重构卷对卷工艺设计
经验分享