[LeetCode] Set Matrix Zeroes
2015-08-15 11:33
239 查看
This problem can be solved easily if we are allowed to use more than O(1) space. For example, you may create a copy of the original matrix (O(mn)-space) or just record the row and column indexes (O(m + n)-space). Well, is there a O(1)-space solution? Yes, you may refer to this link :-)
The key idea is to record the rows and columns that need to be set to zeroes directly in the matrix ( if (!matrix[i][j]) matrix[i][0] = matrix[0][j] = 0; ). The code is rewritten as follows.
The key idea is to record the rows and columns that need to be set to zeroes directly in the matrix ( if (!matrix[i][j]) matrix[i][0] = matrix[0][j] = 0; ). The code is rewritten as follows.
class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); bool c0 = false; for (int i = 0; i < m; i++) { if (!matrix[i][0]) c0 = true; for (int j = 1; j < n; j++) if (!matrix[i][j]) matrix[i][0] = matrix[0][j] = 0; } for (int i = m - 1; i >= 0; i--) { for (int j = n - 1; j; j--) if (!matrix[i][0] || !matrix[0][j]) matrix[i][j] = 0; if (c0) matrix[i][0] = 0; } } };
相关文章推荐
- C# 使用Method进行转换
- spring下的几种注解
- 2-MATLAB数据类型
- 1-基本操作
- 为什么你应该尝试 “全栈”
- XML简介
- C语言:链接属性与存储类型
- 解决Xcode升级,导致以前安装的插件失效的办法
- Java中length(),length,size()的用法和区别
- PyCharm4.5更改字体设置
- 使用C语言解决字符串全排列问题
- 我这三年
- 改变Android Studio中AVD的创建路径
- 安全基础教育第二季第1集:屡战屡败的找回密码
- msgsnd的一个小问题
- Redhat下安装启动Hadoop
- 一个简单的"RPC框架"代码分析
- C#占位符与格式化字符串
- 直方图均衡化的编程实现
- 3-Linear Regression with Multiple Variables