【LeetCode】73. Set Matrix Zeroes (2 solutions)
2024-08-25 07:36:00
Set Matrix Zeroes
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
解法一:
使用数组分别记录需要置零的行列。然后根据数组信息对相应行列置零。
空间复杂度O(m+n)
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
if(matrix.empty() || matrix[].empty())
return; int m = matrix.size();
int n = matrix[].size(); vector<bool> row(m, false);
vector<bool> col(n, false); for(int i = ; i < m; i ++)
{
for(int j = ; j < n; j ++)
{
if(matrix[i][j] == )
{
row[i] = true;
col[j] = true;
}
}
} for(int i = ; i < m; i ++)
{
for(int j = ; j < n; j ++)
{
if(row[i] == true)
matrix[i][j] = ;
if(col[j] == true)
matrix[i][j] = ;
}
}
}
};
解法二:
使用第一行和第一列记录该行和该列是否应该置零。
对于由此覆盖掉的原本信息,只要单独遍历第一行第一列判断是否需要置零即可。
空间复杂度O(1)
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
if(matrix.empty() || matrix[].empty())
return;
int m = matrix.size();
int n = matrix[].size();
bool col0 = false;
bool row0 = false;
for(int i = ; i < m; i ++)
{
if(matrix[i][] == )
{
col0 = true;
break;
}
}
for(int j = ; j < n; j ++)
{
if(matrix[][j] == )
{
row0 = true;
break;
}
}
for(int i = ; i < m; i ++)
{
for(int j = ; j < n; j ++)
{
if(matrix[i][j] == )
{
matrix[][j] = ;
matrix[i][] = ;
}
}
}
for(int i = ; i < m; i ++)
{
if(matrix[i][] == )
{
for(int j = ; j < n; j ++)
{
matrix[i][j] = ;
}
}
}
for(int j = ; j < n; j ++)
{
if(matrix[][j] == )
{
for(int i = ; i < m; i ++)
{
matrix[i][j] = ;
}
}
}
if(col0 == true)
{
for(int i = ; i < m; i ++)
{
matrix[i][] = ;
}
}
if(row0 == true)
{
for(int j = ; j < n; j ++)
{
matrix[][j] = ;
}
}
}
};
最新文章
- ubuntu中用户使用的shell如何指定
- css3 自定义动画(2)位置的移动
- VMware 进入bios
- Application Cache
- shell 全局和局部变量
- 配置SHH集群
- Android 对话框弹出位置和透明度
- 关于谷歌、火狐 右键没有发送到onenote选项
- iOS 中的传值方式
- js中constructor的作用
- js的变量声明以及变量提升
- 离线消息如何实现?-- ESFramework 4.0 快速上手(02)
- Python模块之subprocess--使用Popen来调用系统命令
- 关于 JavaScript 中的继承
- oracle中创建数据库
- SHELL脚本--变量(基础)
- 文档大师 在Win10 IE11下,文档集画面无法正常显示Word等Office文档的解决方法
- webapi 统一处理时间格式
- 空指针、NULL指针、零指针
- Oracle EBS使用adpatch工具打patch过程(hotpatch mode)