LeetCode-73 Set Matrix Zeroes(设置零矩阵)
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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?
public class Solution {
public void setZeroes(int[][] matrix) {
boolean firstX = false;
boolean firstY = false;
for (int i = 0; i < matrix[0].length; i++) {
if (matrix[0][i] == 0) {
firstX = true;
}
}
for (int i = 0; i < matrix.length; i++) {
if (matrix[i][0] == 0) {
firstY = true;
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (int i = 1; i < matrix.length; i++) {//★
for (int j = 1; j < matrix[0].length; j++) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {//▲
matrix[i][j] = 0;
}
}
}
if (firstX) {
for (int i = 0; i < matrix[0].length; i++) {
matrix[0][i] = 0;
}
}
if (firstY) {
for (int i = 0; i < matrix.length; i++) {
matrix[i][0] = 0;
}
}
}
}
Runtime: 331 ms
先将0行的数据是否要清零通过两个布尔型保存,然后在遍历矩阵,将是否置零用边界来保存,然后遍历边界值清零矩阵,最后再处理边界。
PS:有些人的代码里在★多用了个for循环。事实上判断条件修改成▲就可以将两个for循环合并。
然后一开始是这样想的,想通过两个二进制数的0和1来标志行和列是否要取零。。
然而结果是这样的:
155 / 157 test cases passed.
在最后的几个test行和列太多,已经超过了long长度的大小~没法标记了。当然,用字符串什么的就不用说了。字符串=字符数组。空间复杂度还是没提升。
果然大家都认可的一般都是很优化了的。
还是想放出来我这个无法pass的代码。。说明至少从其他角度努力过。。。
public class Solution {
public void setZeroes(int[][] matrix) {
long hang = 0;
long lie = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == 0) {
hang |= (1l<<i);
lie |= (1l<<j);
}
}
}
for (int i = 0; i < matrix.length; i++) {
if ((hang&1) == 1) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = 0;
}
}
hang>>=1;
}
for (int i = 0; i < matrix[0].length; i++) {
if ((lie&1) == 1) {
for (int j = 0; j < matrix.length; j++) {
matrix[j][i] = 0;
}
}
lie>>=1;
}
}
}