LeetCode 73. Set Matrix Zeroes

原题链接在这里:https://leetcode.com/problems/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.

Example 1:

Input: 
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
Output: 
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]

Example 2:

Input: 
[
  [0,1,2,0],
  [3,4,5,2],
  [1,3,1,5]
]
Output: 
[
  [0,0,0,0],
  [0,4,5,0],
  [0,3,1,0]
]

Follow up:

  • 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?

题解:

观察到判断一个数是否应该更改为0 只需要看它的同行同列是否有0就好,所以可以优化成只使用两个 boolean array, 一个记录所有行, 一个记录所有列 是否有0即可, 如此使用O(m+n) space.

更好的方法是使用第一行 和 第一列 来代替额上面的两个记录array, 那么第一行和第一列本来是否需要改成0 呢,其实只需要两个boolean value: firstRow, firstCol 来记录就好,如此只需要使用O(1) space.

Time Complexity: O(m*n).

Space: O(1).

AC Java:

 1 public class Solution {
 2     public void setZeroes(int[][] matrix) {
 3         if(matrix == null || matrix.length == 0){
 4             return;
 5         }
 6         boolean firstRow = false;
 7         boolean firstCol = false;
 8         int m = matrix.length; 
 9         int n = matrix[0].length;
10         
11         //Record if first row, first columna contains 0
12         for(int j = 0; j<n; j++){
13             if(matrix[0][j] == 0){
14                 firstRow = true;
15                 break;
16             }
17         }
18         for(int i = 0; i<m; i++){
19             if(matrix[i][0] == 0){
20                 firstCol = true;
21                 break;
22             }
23         }
24         
25         //first scan, if there are 0, mark its corresponding row and columna as 0 at first column and first row
26         for(int i = 1; i<m; i++){
27             for(int j = 1; j<n; j++){
28                 if(matrix[i][j] == 0){
29                     matrix[0][j] = 0;
30                     matrix[i][0] = 0;
31                 }
32             }
33         }
34         
35         //Scan the matrix for the second time, if corresponding mark is 0, change this element to 0
36         for(int i = 1; i<m; i++){
37             for(int j = 1; j<n; j++){
38                 if(matrix[i][0] == 0 || matrix[0][j] == 0){
39                     matrix[i][j] = 0;
40                 }
41             }
42         }
43         
44         //Change first row and columna at last
45         if(firstRow){
46             for(int j = 0; j<n; j++){
47                 matrix[0][j] = 0;
48             }
49         }
50         if(firstCol){
51             for(int i = 0; i<m; i++){
52                 matrix[i][0] = 0;
53             }
54         }
55     }
56 }

类似Game of Life.

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4868741.html