LeetCode Set Matrix Zeroes
来源:互联网 发布:数据录入项目外包 编辑:程序博客网 时间:2024/05/16 17:15
Description:
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?
Solution:
O(m+n)的空间复杂度比较容易,直接用两个数组将需要设置为0的行号和列号记录下来即可。
import java.util.*;public class Solution {public void setZeroes(int[][] matrix) {int m = matrix.length;int n = matrix[0].length;boolean[] x = new boolean[m];boolean[] y = new boolean[n];for (int i = 0; i < m; i++)for (int j = 0; j < n; j++)if (matrix[i][j] == 0) {x[i] = true;y[j] = true;}for (int i = 0; i < m; i++)if (x[i])Arrays.fill(matrix[i], 0);for (int j = 0; j < n; j++)if (y[j])for (int i = 0; i < m; i++)matrix[i][j] = 0;}}
O(1)的空间复杂的要稍微想一想了。
实际上就是将刚才的两个数组不重新开辟了,而是另外存储到matrix数组当中。
关于如何存储这么操作:
1.首先随机选取一个中心点
2.先判断一下这个点坐在的行、是否需要设置为0(即是否包含0)
3.将其他不在这一行这一列的点进行遍历,需要设置为0的行号和列号保存到当前中心点所在的行列中
4.将标记在中心点所在的行号和列号设置为0
5.将第2步中的判断结果,是否需要设置为0,进行更新
很多其他的结题报告实际上也是用了这样的方法,只不过将这个中心点固定成了点[0,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
- LeetCode Simplify Path
- hdu5275 (插值法)
- action与servlet API ModelDriven接口 异常
- 关于File的一点东西
- Java随机验证吗
- LeetCode Set Matrix Zeroes
- jquery操作select(取值,设置选中) 取得已选的值
- 单例模式 - 创建者模式
- 有关Google面试的资料集合
- android edittext + listview 实现搜索listview中的内容
- Majority Element II
- java-web 第五讲 应用程序的部署 和 会话跟踪
- ssh+spring security+cas搭建(二)
- leetcode解题报告229——Majority Element II