标签:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Given a matrix
[
[1,2],
[0,3]
],
return
[
[0,2],
[0,0]
]
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?
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 not 14 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 column 29 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 elements 39 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 row 48 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 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5675030.html