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.
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?
最简单的想法就是备份另外一个相同矩阵,一个查看一个改,这也是follow up里的第一个解法,显然是bad idea;我们再考虑一下,我们是不是只需要记录有哪些行跟列里有0就行呢,空间复杂度为O(m+n);不使用额外的空间,我没有考虑出来,参考了别人的想法。
O(m+n),我采用了hashset,当然也可以用数组代替,但我感觉hashset更好一点。
public void setZeroes(int[][] matrix) { HashSet<Integer> rowSets = new HashSet<Integer>(); HashSet<Integer> colSets = new HashSet<Integer>(); if (matrix==null || matrix.length==0 || matrix[0].length==0) { return ; } for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if(matrix[i][j]==0){ rowSets.add(i); colSets.add(j); } } } for (Integer row : rowSets) { for (int i = 0; i < matrix[0].length; i++) { matrix[row][i] = 0; } } rowSets.clear(); for (Integer col : colSets) { for (int i = 0; i < matrix.length; i++) { matrix[i][col] = 0; } } colSets.clear(); }不使用额外空间的解法
public void setZeroes(int[][] matrix) { int rownum = matrix.length; if (rownum == 0) return; int colnum = matrix[0].length; if (colnum == 0) return; boolean hasZeroFirstRow = false, hasZeroFirstColumn = false; // Does first row have zero? for (int j = 0; j < colnum; ++j) { if (matrix[0][j] == 0) { hasZeroFirstRow = true; break; } } // Does first column have zero? for (int i = 0; i < rownum; ++i) { if (matrix[i][0] == 0) { hasZeroFirstColumn = true; break; } } // find zeroes and store the info in first row and column for (int i = 1; i < matrix.length; ++i) { for (int j = 1; j < matrix[0].length; ++j) { if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } // set zeroes except the first row and column 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; } } // set zeroes for first row and column if needed if (hasZeroFirstRow) { for (int j = 0; j < colnum; ++j) { matrix[0][j] = 0; } } if (hasZeroFirstColumn) { for (int i = 0; i < rownum; ++i) { matrix[i][0] = 0; } } }