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

运行结果

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

相关推荐
孙小二写代码17 分钟前
[leetcode刷题]面试经典150题之1合并两个有序数组(简单)
算法·leetcode·面试
little redcap23 分钟前
第十九次CCF计算机软件能力认证-1246(过64%的代码-个人题解)
算法
sinat_2765225723 分钟前
C++中move的使用
开发语言·c++
David猪大卫39 分钟前
数据结构修炼——顺序表和链表的区别与联系
c语言·数据结构·学习·算法·leetcode·链表·蓝桥杯
Iceberg_wWzZ41 分钟前
数据结构(Day14)
linux·c语言·数据结构·算法
微尘843 分钟前
C语言存储类型 auto,register,static,extern
服务器·c语言·开发语言·c++·后端
夏天天天天天天天#1 小时前
求Huffman树及其matlab程序详解
算法·matlab·图论
Infedium1 小时前
优数:助力更高效的边缘计算
算法·业界资讯
金博客1 小时前
Qt 模型视图(二):模型类QAbstractItemModel
c++·qt6.7.2
student.J1 小时前
傅里叶变换
python·算法·傅里叶