面试题01.08.零矩阵
链接:面试题01.08.零矩阵
难度:Medium
标签:数组、哈希表、矩阵
简介:编写一种算法,若 M × N 矩阵中某个元素为 0,则将其所在的行与列清零。
题解 1 - cpp
- 编辑时间:2022-09-30
- 执行用时:12ms
- 内存消耗:11.9MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int n = matrix.size(), m = matrix[0].size();
        unordered_set<int> rows, cols;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (matrix[i][j] == 0) {
                    rows.insert(i);
                    cols.insert(j);
                }
            }
        }
        for (auto &row : rows) {
            for (int i = 0; i < m; i++) matrix[row][i] = 0;
        }
        for (auto &col : cols) {
            for (int i = 0; i < n; i++) matrix[i][col] = 0;
        }
    }
};