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

LeetCode第73题矩阵置零
1.思路: 想到一个开辟一点空间来解决方法,使用哈希集。就是使用一个哈希集(row和col)来储存数组中的元素为0的下标。然后再遍历,整个二维数组,在哈希集中存在对应的下标,就将这一行或这一列置为0。
2.代码部分

cpp 复制代码
#include<iostream>
#include<vector>
#include <unordered_set> 
using namespace std;


class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        unordered_set<int> row;  //记录横坐标
        unordered_set<int> col;  //记录纵坐标
        for (int i = 0; i < matrix.size(); i++) {
            for (int j = 0; j < matrix[0].size(); j++) {
                if (matrix[i][j] == 0) {
                    row.insert(i);
                    col.insert(j);
                }
            }
        }
        for (int i = 0; i < matrix.size(); i++) {
            for (int j = 0; j < matrix[0].size(); j++) {
                if (row.count(i) || col.count(j)) {
                	matrix[i][j] = 0;
                }
            }
        } 
    }
    
};
相关推荐
eggwyw1 天前
C++ union 的一种妙用法
开发语言·c++
ShineWinsu1 天前
对于Qt:QHBoxLayout常见属性以及方法的解析
c++·qt·面试·gui·客户端·布局管理器·水平布局器
小七在进步1 天前
string的实现(1)
c++·笔记·visual studio
敲上瘾1 天前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
牢姐与蒯1 天前
cpp算法之哈希
c++·算法·哈希算法
lcj25111 天前
[C++] C++11
开发语言·c++·笔记
tellmewhoisi1 天前
深度学习0:数学知识:(雅可比矩阵)
人工智能·深度学习·矩阵
小小bugbug1 天前
带工作窃取的线程池
c++·线程池
南风84112 天前
C++ 四种强制类型转换详解
c++
微笑星河q2 天前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++