链接:
https://leetcode.com/problems/set-matrix-zeroes/
大意:
给定一个二维数组,二维数组中每个元素为1或者0。要求把原二维数组中每个0所在的行和列的元素都变为0。最佳解法为O(1)空间复杂度。例子:
思路:
使用两个一维数组rows以及cols存储原二维数组中元素为0的行和列(即若matrix[i][j] == 0,则rows[i] = 1,cols[j] = 1)。之后对于rows中每个元素,若rows[i] == 1,则将matrix中第i行全置为0;对于cols中每个元素,若rows[j] == 1,则将matrix中第j列全置为0。此解法时间复杂度O(m*n),空间复杂度O(m+n)
代码:(非最佳)
class Solution {
public void setZeroes(int[][] matrix) {
if (matrix.length == 0)
return ;
int[] rows = new int[matrix.length], cols = new int[matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == 0) {
rows[i] = 1;
cols[j] = 1;
}
}
}
for (int i = 0; i < rows.length; i++) {
if (rows[i] == 1) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = 0;
}
}
}
for (int j = 0; j < cols.length; j++) {
if (cols[j] == 1) {
for (int i = 0; i < matrix.length; i++) {
matrix[i][j] = 0;
}
}
}
}
}
结果:
结论:
该解法非最佳。一开始是使用两个Set分别存储值为0的行和列,后面提交后运行时长2ms,太慢... 于是想到用计数数组代替哈希表(毕竟数组是不用解决冲突且访问元素是O(1)时间复杂度)。所以,以后能用数组解决的问题就尽量不要用其他数据结构!
最佳代码:(感觉很复杂,以后有时间再看)
public void setZeroes(int[][] matrix) {
int num_rows = matrix.length;
int num_cols = matrix[0].length;
boolean flag_for_first_row = false;
boolean flag_for_first_col = false;
// Check if there is any zero in first row, and set flag, we will use this later.
for(int col=1;col<num_cols;col++) {
if(matrix[0][col] == 0) {
flag_for_first_row = true;
break;
}
}
// Check if there is any zero in second row, and set flag.
for(int row=1;row<num_rows;row++) {
if(matrix[row][0] == 0) {
flag_for_first_col = true;
break;
}
}
// Check if there is a zero in the matrix(except first row and column),
// If we found a zero, place the zero in first row and column.
for(int row=1;row<num_rows;row++) {
for(int col=1;col<num_cols;col++) {
if(matrix[row][col] == 0) {
matrix[0][col] = 0;
matrix[row][0] = 0;
}
}
}
// Traverse first row and columns (below 2 for loops) and fillup the corresponding rows and columns.
for(int col=1;col<num_cols;col++) {
if(matrix[0][col] == 0) {
for(int row=1;row<num_rows;row++) {
matrix[row][col] = 0;
}
}
}
for(int row=1;row<num_rows;row++) {
if(matrix[row][0] == 0) {
for(int col=1;col<num_cols;col++) {
matrix[row][col] = 0;
}
}
}
// Check if the [0][0] element is zero or not, if yes, replace the first row and columns with zero.
if(matrix[0][0] == 0) {
for(int col=0;col<num_cols;col++) matrix[0][col] = 0;
for(int row=0;row<num_rows;row++) matrix[row][0] = 0;
} else {
// Now the only thing which remains is, is to check whether there
// was a zero in the first col or row before.
if(flag_for_first_row) for(int col=0;col<num_cols;col++) matrix[0][col] = 0;
if(flag_for_first_col) for(int row=0;row<num_rows;row++) matrix[row][0] = 0;
}
}