73. Set Matrix Zeroes

https://leetcode.com/problems/set-matrix-zeroes/tabs/description

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

 

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?

 Sol 1:
 
class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        
        # Space O(m+n)  
        # remember index of rows and columns with zero.
        
        rows = []
        cols = []
        
        rowNum = len(matrix)
        colNum = len(matrix[0])
        
        # detect zeors and remember their row and col index.
        for i in range(rowNum):
            for j in range(colNum):
                if matrix[i][j] == 0:
                    rows.append(i)
                    cols.append(j)
                    
        # set marked cols and rows to zeros
        for row in rows:
            for col in range(colNum):
                matrix[row][col] = 0
                
        for col in cols:
            for row in range(rowNum):
                matrix[row][col] = 0
        
        

Sol 2:

Java

public class Solution {
    public void setZeroes(int[][] matrix) { 
        
        // Time O(m*n) Space O(1)
        
        final int m = matrix.length;
        final int n = matrix[0].length;
        boolean row_has_zero = false; // check if the first row has 0
        boolean col_has_zero = false; // check if the first col has 0
        
        
        for (int i = 0; i < n; i++)
            if (matrix[0][i] == 0) {
                row_has_zero = true;
                break;
                }
        
        
        for (int i = 0; i < m; i++)
                if (matrix[i][0] == 0) {
                col_has_zero = true;
                break;
                }
        
        
        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++)
                if (matrix[i][j] == 0) {
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
        
        
        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++)
                if (matrix[i][0] == 0 || matrix[0][j] == 0)
                matrix[i][j] = 0;
        
        
        if (row_has_zero)            
            for (int i = 0; i < n; i++)
                matrix[0][i] = 0;
        if (col_has_zero)
            for (int i = 0; i < m; i++)
                matrix[i][0] = 0;
    }
};
原文地址:https://www.cnblogs.com/prmlab/p/7246042.html