標籤:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Have you met this question in a real interview? YesExample
Given a matrix
[ [1,2], [0,3]],
return
[
[0,2],
[0,0]
]
Challenge
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?
Analysis: We are going to use two sets to save all the column numbers and row numbers whose cells need to be set to 0. This will cost O(m + n) space. Another approach is from: http://fisherlei.blogspot.com/2013/01/leetcode-set-matrix-zeroes.html1.先確定第一行和第一列是否需要清零
2.掃描剩下的矩陣元素,如果遇到了0,就將對應的第一行和第一列上的元素賦值為0
3.根據第一行和第一列的資訊,已經可以講剩下的矩陣元素賦值為結果所需的值了
4.根據1中確定的狀態,處理第一行和第一列。
1 public class Solution { 2 /** 3 * @param matrix: 4 * A list of lists of integers 5 * @return: Void 6 */ 7 public void setZeroes(int[][] matrix) { 8 if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return; 9 10 boolean firstRowZero = false;11 boolean firstColumnZero = false;12 13 // set first row and column zero or not14 for (int i = 0; i < matrix.length; i++) {15 if (matrix[i][0] == 0) {16 firstColumnZero = true;17 break;18 }19 }20 21 for (int i = 0; i < matrix[0].length; i++) {22 if (matrix[0][i] == 0) {23 firstRowZero = true;24 break;25 }26 }27 28 // mark zeros on first row and column29 for (int i = 1; i < matrix.length; i++) {30 for (int j = 1; j < matrix[0].length; j++) {31 if (matrix[i][j] == 0) {32 matrix[i][0] = 0;33 matrix[0][j] = 0;34 }35 }36 }37 38 // use mark to set elements39 for (int i = 1; i < matrix.length; i++) {40 for (int j = 1; j < matrix[0].length; j++) {41 if (matrix[i][0] == 0 || matrix[0][j] == 0) {42 matrix[i][j] = 0;43 }44 }45 }46 47 // set first column and row48 if (firstColumnZero) {49 for (int i = 0; i < matrix.length; i++)50 matrix[i][0] = 0;51 }52 53 if (firstRowZero) {54 for (int i = 0; i < matrix[0].length; i++)55 matrix[0][i] = 0;56 }57 }58 }
Set Matrix Zeroes