73. 矩阵置零

给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。

示例 1:

输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
输出:[[1,0,1],[0,0,0],[1,0,1]]

示例 2:

  • 输入:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
    输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]

提示:

  • m == matrix.length
  • n == matrix[0].length
  • 1 <= m, n <= 200
  • -231 <= matrix[i][j] <= 231 - 1

法1:标记数组

cpp 复制代码
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        vector<bool> flagRow(matrix.size(),false);
        vector<bool> flagCol(matrix[0].size(),false);
        for(int row = 0;row<matrix.size();row++){
            for(int col = 0;col<matrix[0].size();col++){
                if(matrix[row][col]==0){
                    flagRow[row] = true;
                    flagCol[col] = true;
                }
            }
        }
        for(int row = 0;row<matrix.size();row++){
            for(int col = 0;col<matrix[0].size();col++){
                if (flagRow[row]||flagCol[col]){
                    matrix[row][col] = 0;
                }
            }
        }


    }
};
相关推荐
郝学胜-神的一滴15 分钟前
Leetcode 969 煎饼排序✨:翻转间的数组排序艺术
数据结构·c++·算法·leetcode·面试
炸膛坦客7 小时前
单片机/C/C++八股:(二十)指针常量和常量指针
c语言·开发语言·c++
I_LPL8 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
颜酱8 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
WolfGang0073218 小时前
代码随想录算法训练营 Day16 | 二叉树 part06
算法
炸膛坦客9 小时前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
2401_8318249610 小时前
代码性能剖析工具
开发语言·c++·算法
是wzoi的一名用户啊~10 小时前
【C++小游戏】2048
开发语言·c++
Sunshine for you10 小时前
C++中的职责链模式实战
开发语言·c++·算法
qq_4160187211 小时前
C++中的状态模式
开发语言·c++·算法