LeetCode Set Matrix Zeroes



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

题意:给出一个m*n的矩阵,如果一个元素为0,将其所在的行及列全部置为0

思路:先扫描矩阵,将0元素的行及列记录下来,然后再一次扫描矩阵,如果当前扫描元素的行或者列包含在记录中,就将其置为0

代码如下

public class Solution {
    public void setZeroes(int[][] matrix)
    {
        int row = matrix.length;
        int col = row > 0 ? matrix[0].length : 0;

        HashSet<Integer> rowset = new HashSet<Integer>();
        HashSet<Integer> colset = new HashSet<Integer>();

        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                if (matrix[i][j] == 0)
                {
                    rowset.add(i);
                    colset.add(j);
                }
            }
        }

        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                if (colset.contains(j) || rowset.contains(i))
                {
                    matrix[i][j] = 0;
                }
            }
        }
    }
}

你可能感兴趣的:(LeetCode Set Matrix Zeroes)