首页 > 技术文章 > 73. Set Matrix Zeroes

joannacode 2016-11-26 14:40 原文

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

click to show follow up.

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?

Time O(nm) space O(N+M)
public class Solution {
    public void setZeroes(int[][] matrix) {
        int col = matrix[0].length;
        int row = matrix.length;
        HashSet<Integer> row0 = new HashSet<>();
        HashSet<Integer> col0 = new HashSet<>();
        for(int i = 0 ; i < row ; i++){
            for(int j = 0 ; j < col; j++){
                if(matrix[i][j] == 0){
                    row0.add(i);
                    col0.add(j);
                }
            }
        }
        for(int i : row0){
            for(int j = 0 ; j < col; j++){
                matrix[i][j] = 0;
            }
        }
        
        for(int i : col0){
            for(int j = 0 ; j < row; j++){
                matrix[j][i] = 0;
            }
        }
    }
}

 

法二 : no space

   用每行的第一个 和每列的第一来存0,注意清零时不能用第一列和第一行 否则会相互影响。

    //No extra space  只要有0,用该row或者该col的第一个值存0
    public void setZeroes(int[][] matrix) {
        int col = matrix[0].length;
        int row = matrix.length;
        int col0 = 1;
        for(int i = 0 ; i < row ; i++){
            if (matrix[i][0] == 0) col0 = 0;
            for(int j = 1 ; j < col; j++){
                if(matrix[i][j] == 0){
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;   
                }
            }
        }
        for(int i = row -1 ; i >= 0 ; i--){
            for(int j = col - 1 ; j >= 1; j--){
                if(matrix[i][0] == 0 ||  matrix[0][j] == 0)
                    matrix[i][j] = 0;
            }
        }
        
        if(col0 == 0){
            for(int i = 0; i < row ; i++){
                matrix[i][0] = 0;
            }
        }
    }

 

推荐阅读