Leetcode.面试题 01.08 零矩阵

首页 / 💻 代码 / 正文

题目简介

编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。


代码模板

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {

    }
};

最终代码

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int n_hang, n_lie;
        n_lie = matrix.size();
        n_hang = matrix[0].size();
        vector<vector<int>> Zero_location;
        for(int ncptime=1;ncptime<=n_lie;ncptime++)
            for (int cptime = 1; cptime <= n_hang; cptime++)
            {
                if (matrix[ncptime - 1][cptime - 1] == 0)
                {
                    Zero_location.push_back(vector<int>{ncptime,cptime});
                }
            }
        int n_zero_lie = Zero_location.size();
        for (int i = 1; i <= n_zero_lie; i++)
        {
            int j_lie = Zero_location[i - 1][0];
            int j_hang = Zero_location[i - 1][1];
            for (int m = 1; m <= n_hang; m++)
            {
                matrix[j_lie-1][m - 1] = 0;
            }
            for (int q = 1; q <= n_lie; q++)
            {
                matrix[q - 1][j_hang - 1] = 0;
            }

        }

    }
};

属于是用空间复杂度换时间复杂度了。
{73E3A4D4-27EB-4c5f-A9EC-FA5C681621C3}.png


打赏qwq
文章目录