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
原创粉丝点击