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.

click to show follow up.

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] = ;
}
}
}
};

最新文章

  1. ubuntu中用户使用的shell如何指定
  2. css3 自定义动画(2)位置的移动
  3. VMware 进入bios
  4. Application Cache
  5. shell 全局和局部变量
  6. 配置SHH集群
  7. Android 对话框弹出位置和透明度
  8. 关于谷歌、火狐 右键没有发送到onenote选项
  9. iOS 中的传值方式
  10. js中constructor的作用
  11. js的变量声明以及变量提升
  12. 离线消息如何实现?-- ESFramework 4.0 快速上手(02)
  13. Python模块之subprocess--使用Popen来调用系统命令
  14. 关于 JavaScript 中的继承
  15. oracle中创建数据库
  16. SHELL脚本--变量(基础)
  17. 文档大师 在Win10 IE11下,文档集画面无法正常显示Word等Office文档的解决方法
  18. webapi 统一处理时间格式
  19. 空指针、NULL指针、零指针
  20. Oracle EBS使用adpatch工具打patch过程(hotpatch mode)

热门文章

  1. 【弱省胡策】Round #0 Flower Dance DP
  2. Linux下ip route、ip rule、iptables的关系(转)
  3. ubuntu下从源码编译安装cherokee
  4. 对jQuery的事件绑定的一些思考
  5. MySQL round函数
  6. 如何修改容器内的/etc/resolv.conf
  7. Maven配置浅析
  8. 使用Vue.js制作仿Metronic高级表格(一)静态设计
  9. 如何设置ESXi中的虚拟机随主机一同启动?
  10. vue中的css作用域、vue中的scoped坑点