leetcode--Set Matrix Zeroes
2015-06-08 15:47
489 查看
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?
题意:给定m*n的矩阵,如果某个元素是0,使其同行,同列的所有元素为0
要求使用O(m+n)空间复制度,甚至常数空间
解法1:首先遍历第一行,如果找到0,做标记,说明第一行要清0
遍历第一列,如果找到0,做标记,说明第一列要清0
然后从(1,1)开始遍历矩阵,找到0,将对应的第一行,第一列的元素设置为0,用于标记该行列应该清0
最后,根据第一行,第一列,0的情况,清0
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?
题意:给定m*n的矩阵,如果某个元素是0,使其同行,同列的所有元素为0
要求使用O(m+n)空间复制度,甚至常数空间
解法1:首先遍历第一行,如果找到0,做标记,说明第一行要清0
遍历第一列,如果找到0,做标记,说明第一列要清0
然后从(1,1)开始遍历矩阵,找到0,将对应的第一行,第一列的元素设置为0,用于标记该行列应该清0
最后,根据第一行,第一列,0的情况,清0
public class Solution { public void setZeroes(int[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; boolean firstRow=false,firstCol=false; for(int i=0;i<rows;i++){ if(matrix[i][0]==0){ firstRow = true; break; } } for(int i=0;i<cols;i++){ if(matrix[0][i]==0){ firstCol = true; break; } } for(int i=1;i<rows;i++){ for(int j=1;j<cols;j++){ if(matrix[i][j]==0){ matrix[i][0] = 0; matrix[0][j] = 0; } } } for(int i=1;i<rows;i++){ if(matrix[i][0]==0){ for(int j=1;j<cols;j++){ matrix[i][j] = 0; } } } for(int j=1;j<cols;j++){ if(matrix[0][j]==0){ for(int i=1;i<rows;i++){ matrix[i][j] = 0; } } } if(firstRow) for(int i=0;i<rows;i++) matrix[i][0] = 0; if(firstCol) for(int j=0;j<cols;j++) matrix[0][j] = 0; } }
相关文章推荐
- 程序员的量化交易之路(30)--Cointrader之ConfigUtil(17)
- 不能将类型“ZhangKong.Hotel.HRModels.Models.Basic.HR_TimeQuantum”用作泛型类型或方法“ZhangKong.Hotel.Repository.Impl
- tcp_tw_reuse、tcp_tw_recycle 使用场景及注意事项
- 使用正则表达式解决CSV文件导入问题
- HDU2815 Mod Tree 高次同余方程
- android google服务框架安装
- linux(CentOS7)安装cuda
- 查找矩阵中是否存在一个数
- 老版本PHP转义Json里的特殊字符的函数
- Intent和PendingIntent的区别
- puppet学习笔记之安装与配置
- Ext.grid 刷新后选中指定行
- 结合轮廓显示,实现完整的框选目标(附Demo代码)
- 完成端口(Completion Port)详解----- By PiggyXP(小猪)
- Aspose Cells 控件如何实现数据过滤(附代码和下载地址)
- GRE写作之优秀的高效的领导者的特征
- oracle translate函数
- GRE写作高分经验分享之勤修改作文
- linux 模块编程
- Win10 7月底完成正式版 你的显卡硬件支持DX12吗?