LeetCode-73. Set Matrix Zeroes

来源:互联网 发布:周五非农就业数据 编辑:程序博客网 时间:2024/06/10 11:52

问题描述

  1. 给定一个m*n的数组,如果数组中某个位置的元素为0,则将该行该列的元素全部置零。
  2. 例如[ [1,2,0],[2,4,1] ],返回[ [0,0,0],[2,4,0]].

解题思路

  1. 首先想到的是利用两个set来存储矩阵值为0的行和列,遍历完矩阵后根据set中记录的行列信息来置零。
  2. 或者可以利用两个boolean数组,分别记录矩阵中元素为0的行列信息。因为觉得用set判断某个位置是否在set中,而如果利用数组的话可以直接定位。

代码

import java.util.*;public class Solution {    public void setZeroes(int[][] matrix) {        if(matrix==null || matrix.length==0)            return;        //Set<Integer> row=new HashSet<Integer>();        //Set<Integer> col=new HashSet<Integer>();        boolean [] row=new boolean[matrix.length];        boolean[] col=new boolean[matrix[0].length];        for(int i=0;i<matrix.length;i++){            for(int j=0;j<matrix[0].length;j++){                if(matrix[i][j]==0){                    row[i]=true;                    col[j]=true;                }            }        }        for(int i=0;i<matrix.length;i++){            if(row[i]){               for(int j=0;j<matrix[0].length;j++)                    matrix[i][j]=0;            }        }        for(int j=0;j<matrix[0].length;j++){            if(col[j]){                for(int i=0;i<matrix.length;i++)                    matrix[i][j]=0;            }        }    }}
原创粉丝点击