1. 程式人生 > >73. Set Matrix Zeroes - Medium

73. Set Matrix Zeroes - Medium

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?

 

把第一行和第一列的元素當作flag,表示這一行/列有無0

首先掃描matrix,如果有元素為0,就把該元素所在的行、列的第一個元素設為0,作為稍後整體設零的flag

注意第一行和第一列的處理!!如果第一行/列有0,用另外的flag表示,最後再處理這兩部分。如果一開始就設0的話,整個矩陣都會變成0

掃描第一行,如果有0,就把當前列全部設為0;掃描第一列,如果有0,就把當前行全部設為0

最後處理第一行/列,如果有0的話

time: O(M * N), space: O(1)

class Solution {
    public void setZeroes(int[][] matrix) {
        if(matrix == null || matrix.length == 0) return;
        int m = matrix.length, n = matrix[0].length;
        
boolean rowHasZero = false, colHasZero = false; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(matrix[0][j] == 0) rowHasZero = true; if(matrix[i][0] == 0) colHasZero = true; } } for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } for(int i = 1; i < m; i++) { if(matrix[i][0] == 0) { for(int j = 1; j < n; j++) matrix[i][j] = 0; } } for(int j = 1; j < n; j++) { if(matrix[0][j] == 0) { for(int i = 1; i < m; i++) matrix[i][j] = 0; } } if(colHasZero) { for(int i = 0; i < m; i++) matrix[i][0] = 0; } if(rowHasZero) { for(int j = 0; j < n; j++) matrix[0][j] = 0; } } }

 

改進:少一個pass

class Solution {
    public void setZeroes(int[][] matrix) {
        if(matrix == null || matrix.length == 0) return;
        int m = matrix.length, n = matrix[0].length;
        boolean rowHasZero = false, colHasZero = false;
        
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                    if(j == 0) colHasZero = true;
                    if(i == 0) rowHasZero = true;
                }
            }
        }
        
        for(int i = 1; i < m; i++) {
            if(matrix[i][0] == 0) {
                for(int j = 1; j < n; j++)
                    matrix[i][j] = 0;
            }
        }
        for(int j = 1; j < n; j++) {
            if(matrix[0][j] == 0) {
                for(int i = 1; i < m; i++)
                    matrix[i][j] = 0;
            }
        }
        
        if(colHasZero) {
            for(int i = 0; i < m; i++)
                matrix[i][0] = 0;
        }
        if(rowHasZero) {
            for(int j = 0; j < n; j++)
                matrix[0][j] = 0;
        }
    }
}