当前位置:网站首页>【LeetCode】73.矩阵置零
【LeetCode】73.矩阵置零
2022-07-31 10:03:00 【酥酥~】
题目
给定一个 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
进阶:
一个直观的解决方案是使用 O(mn) 的额外空间,但这并不是一个好的解决方案。
一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。
你能想出一个仅使用常量空间的解决方案吗?
题解
设置两个一维数组row和col
遇到0则对其所在行列进行记录
最后更新
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
vector<bool> row(m,false);
vector<bool> col(n,false);
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(matrix[i][j]==0)
{
row[i] = true;
col[j] = true;
}
}
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(row[i] || col[j])
matrix[i][j]=0;
}
}
}
};
使用第一行和第一列来记录该行该列是否需要置零
同时使用两个变量记录第一行和第一列是否需要置零
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
bool flag_row0 = false;
bool flag_col0 = false;
for(int i=0;i<m;i++)//第一列是否需要置零
{
if(matrix[i][0]==0)
flag_col0 = true;
}
for(int j=0;j<n;j++)//第一行是否需要置零
{
if(matrix[0][j]==0)
flag_row0 = true;
}
for(int i=1;i<m;i++)//从(1,1)开始,遇到0则标记对零的行和列的第一个元素
{
for(int j=1;j<n;j++)
{
if(matrix[i][j]==0)
{
matrix[i][0] = matrix[0][j] = 0;
}
}
}
for(int i=1;i<m;i++)
{
for(int j=1;j<n;j++)
{
if(matrix[i][0]==0 || matrix[0][j]==0)
matrix[i][j]=0;
}
}
if(flag_row0)
{
for(int i=0;i<n;i++)
{
matrix[0][i] = 0;
}
}
if(flag_col0)
{
for(int i=0;i<m;i++)
{
matrix[i][0] = 0;
}
}
}
};
边栏推荐
猜你喜欢

Burndown chart of project management tools: Dynamic assessment of team work ability

Android安全专题(三)JNI混淆
![[NLP] Interpretation of Transformer Theory](/img/5f/8e1b9e48310817a0443eb445479045.png)
[NLP] Interpretation of Transformer Theory

多个js雷达图同时显示

The future of the hybrid interface: conversational UI

VMware下安装win10启动后进入Boot Manger界面如何解决

如何将亚马逊广告添加到您的 WordPress 网站(3 种方法)

js部门预算和支出雷达图

数据中台建设(六):数据体系建设

Redis Cluster - Sentinel Mode Principle (Sentinel)
随机推荐
【GORM】存取数组/自定义类型数据
乐观锁和悲观锁
【23提前批】北森云计算-测开面经
Module eight
cocoaPods管理之后工程结构变化
第五章
Source code analysis of GZIPInputStream class
金鱼哥RHCA回忆录:CL210管理OPENSTACK网络--开放虚拟网络(OVN)简介(课后练习)
Kotlin—基本语法 (四)
如何优雅的停止一个线程?
因存在自燃安全隐患,宝马7系和5系紧急召回,合计超过5.7万辆
loadrunner-Controller负载测试-各模块功能记录01测试场景设计
来n遍剑指--06. 从尾到头打印链表
Scala basics [seq, set, map, tuple, WordCount, queue, parallel]
The future of the hybrid interface: conversational UI
The big-eyed Google Chrome has also betrayed, teach you a trick to quickly clear its own ads
NowCoderTOP17-22 Binary search/sort - continuous update ing
Kotlin—基本语法(三)
作为面试官,关于线程池的问题我一般这样套路...
NowCoderTOP17-22 二分查找/排序——持续更新ing