Leetcode 73. Set Matrix Zeroes

本文介绍了解决矩阵中置零问题的两种方法。一种是使用额外的行和列数组来记录需要置零的位置,另一种是在矩阵的第一行和第一列中直接进行标记,避免了额外的空间消耗。通过这两种方法,可以有效地将包含零元素的行和列全部置零。

文章作者:Tyan
博客:noahsnail.com  |  优快云  |  简书

1. Description

Set Matrix Zeroes

2. Solution

  • Version 1
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int rows = matrix.size();
        if(rows == 0) {
            return;
        }
        int columns = matrix[0].size();
        vector<int> row;
        vector<int> column;
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < columns; j++) {
                if(!matrix[i][j]) {
                    row.push_back(i);
                    column.push_back(j);
                }
            }
        }
        for(int i = 0; i < row.size(); i++) {
            for(int j = 0; j < columns; j++) {
                matrix[row[i]][j] = 0;
            }
        }
        for(int j = 0; j < column.size(); j++) {
            for(int i = 0; i < rows; i++) {
                matrix[i][column[j]] = 0;
            }
        }
    }
};
  • Version 2
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int rows = matrix.size();
        if(rows == 0) {
            return;
        }
        int columns = matrix[0].size();
        bool row = false;
        bool column = false;
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < columns; j++) {
                if(!matrix[i][j]) {
                    if(!i) {
                        row = true;
                    }
                    if(!j) {
                        column = true;
                    }
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }
        for(int i = 1; i < rows; i++) {
            for(int j = 1; j < columns; j++) {
                if(!matrix[0][j] || !matrix[i][0]) {
                    matrix[i][j] = 0;
                }
            }
        }
        if(row) {
            for(int j = 0; j < columns; j++) {
                matrix[0][j] = 0;
            } 
        }
        if(column) {
            for(int i = 0; i < rows; i++) {
                matrix[i][0] = 0;
            }
        }
    }
};

Reference

  1. https://leetcode.com/problems/set-matrix-zeroes/description/
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值