Set Matrix Zeroes
来源:互联网 发布:存货管理毕业论文数据 编辑:程序博客网 时间:2024/04/29 19:02
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?
class Solution {public: void setZeroes(vector<vector<int> > &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function int m = matrix.size(); if (m<=0) return; int n = matrix[0].size(); if (n<=0) return; bool row=false; bool col=false; for(int i=0; i< n; i++){ if (matrix[0][i] == 0){ row = true; break; } } for(int i=0; i< m; i++){ if (matrix[i][0] == 0){ col = true; break; } } for(int i = 0; i < n; i++) for(int j = 0; j<m; j++){ if (matrix[j][i] == 0){ matrix[j][0] = 0; matrix[0][i] =0; } } for(int i =1; i < n; i++) for(int j = 1; j<m; j++){ if (matrix[j][0] == 0 || matrix[0][i] == 0) matrix[j][i]=0; } if (row == true){ for (int i = 0; i < n; i++) matrix[0][i] = 0; } if (col == true){ for (int i = 0; i < m; i++) matrix[i][0] = 0; } }};
不得不再提醒自己,不要想着一次性得到最优解,先写一个简单的,思路清晰,bugfree最重要!!
1. 对于 O(m + n) 可以用vector,减少时间 O(nm)前面的系数
2. 对于 constant space,就牺牲点时间复杂度好了。 同first missing positive number,利用数据本身做存储,以达到constant memory的目的
最开始的时候想把两个都点都集中起来,天呢,麻烦死了……又是swap,又是判断的……
3.
for(int i =1; i < n; i++) for(int j = 1; j<m; j++){ if (matrix[j][0] == 0 || matrix[0][i] == 0) matrix[j][i]=0; }最开始这里面的1都用0代替,明显不该用的信息别我用了,导致出现全0
- LeetCode: Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- LeetCode Set Matrix Zeroes
- [Leetcode] Set Matrix Zeroes
- LeetCode: Set Matrix Zeroes
- Set Matrix Zeroes
- Leetcode: Set Matrix Zeroes
- [LeetCode] Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- [LeetCode]Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- [leetcode]Set Matrix Zeroes
- Leetcode:Set Matrix Zeroes
- Set Matrix Zeroes
- spi 通信的要点 pic24f 为例
- 网络最流行的伤感时代空间日志发布:那一年,我们十六、七岁
- API自动化软件测试之我见
- Web设计的8大趋势
- 6个重要的.NET概念:栈,堆,值类型,引用类型,装箱,拆箱
- Set Matrix Zeroes
- android 使用广播监听网络状态
- 各主流工作流引擎算法
- VC++中DEBUG的一个无法类型转化的问题
- Struts 2简单配置分析,让Struts 2运行起来!
- KEIL V9.0可用的注册机
- tomcat server.xml中文版
- 伤感语录:浅唱,没人懂的悲伤
- C++ 文件操作笔记