美文网首页
Set Matrix Zeros

Set Matrix Zeros

作者: yanyuchen | 来源:发表于2017-07-24 08:39 被阅读0次

    解题报告: 因为不要用extra space 所以运行时间可能有点高,主要是两个方法, 一个是找出这些零的位置,之后用第二个方法将它的纵和横都改成零。

    public class Solution {    public void setZeroes(int[][] matrix) {        if(matrix == null || matrix.length == 0|| matrix[0].length == 0) return;        int m = matrix.length;        int n = matrix[0].length;        //find which row and which column        HashMap> map = new HashMap<>();                for(int i = 0; i < m; i++){            for(int j = 0; j < n; j++){                              if(matrix[i][j] == 0){                  if(!map.containsKey(i)){                      ArrayListtemp = new ArrayList<>();

    temp.add(j);

    map.put(i, temp);

    }else{

    map.get(i).add(j);

    }

    }

    }

    }

    for(int i = 0; i < m;i++){

    if(map.containsKey(i)){

    for(Integer j: map.get(i)){

    set(matrix, i, j);

    }

    }

    }

    return;

    }

    private void set(int[][] matrix, int i, int j){

    //  if(i <= matrix.length || j <= matrix[0].length) return;

    if(matrix == null || matrix.length == 0|| matrix[0].length == 0) return;

    for(int k = 0; k < matrix[0].length; k++){

    matrix[i][k] = 0;

    }

    for(int l = 0; l < matrix.length; l++){

    matrix[l][j] = 0;

    }

    return;

    }

    }

    相关文章

      网友评论

          本文标题:Set Matrix Zeros

          本文链接:https://www.haomeiwen.com/subject/wivvkxtx.html