Leetcode-set-matrix-zeroes
来源:互联网 发布:网络招聘哪个好 编辑:程序博客网 时间:2024/06/07 03:18
题目描述
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。
因为都是置0,我们在循环查到找到以后,如果直接将所在列和所在行的数全部置0,则继续往后遍历时,算法会分不清0是原来的元素还是更改后的。
所以解决方法是:一开始找到所有的0,把这些值置为Integer.MAX_VALUE-1,然后完成更改,遍历完成后,再把所有的Integer.MAX_VALUE-1变回0。
注意不能使用如下方法:
public class Solution { public void setZeroes(int[][] matrix) { int m = matrix.length; if(m == 0) return; int n = matrix[0].length; int x = Integer.MAX_VALUE - 1; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(matrix[i][j] == 0){ matrix[i][j] = x; } } } for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(matrix[i][j] == x){ for(int k=0;k<n;k++){ if(matrix[i][k]!=x) matrix[i][k]=0; } for(int k=0;k<m;k++){ if(matrix[k][j]!=x) matrix[k][j]=0; } } } } for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(matrix[i][j] == x){ matrix[i][j] = 0; } } } }}
0 0
- LeetCode: Set Matrix Zeroes
- LeetCode Set Matrix Zeroes
- [Leetcode] Set Matrix Zeroes
- LeetCode: Set Matrix Zeroes
- Leetcode: Set Matrix Zeroes
- [LeetCode] Set Matrix Zeroes
- [LeetCode]Set Matrix Zeroes
- [leetcode]Set Matrix Zeroes
- Leetcode:Set Matrix Zeroes
- LeetCode-Set Matrix Zeroes
- [leetcode] Set Matrix Zeroes
- LeetCode - Set Matrix Zeroes
- Set Matrix Zeroes leetcode
- 【Leetcode】Set Matrix Zeroes
- 【leetcode】Set Matrix Zeroes
- Leetcode: Set Matrix Zeroes
- Leetcode Set Matrix Zeroes
- LeetCode | Set Matrix Zeroes
- poj 2481
- java程序设计第一课 jdk安装与配置 java可以执行javac却不可以的解决方法
- C++, Define A Type Member
- 重新温习1--数学归纳法
- IOS NSPredicate 查询、搜索
- Leetcode-set-matrix-zeroes
- Android录音功能Android Studio实现
- Linux下如何搭建stm32开发环境
- Msql注入方式收集 发布时间:2016年6月9日 / 分类:抛砖引玉 / 1,081 次围观 / 2 次吐槽
- cookie乱码
- atom markdown转换PDF 解决AssertionError: html-pdf: Failed to load PhantomJS module
- 文件(字符)读写
- ClassNotFoundException: org.apache.axis2.transport.http.AxisAdminServlet(亲测,管用!已经在这个网站解决好多问题了)
- hdu 2962 Trucking【二分+SPFA】