【LeetCode】Set Matrix Zeroes

Set Matrix Zeroes
Total Accepted: 6043 Total Submissions: 20253 My Submissions
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.
题目不难,但是要特别注意,修改matrix的时候将所有的数据都置为0。
思路是,扫描一遍矩阵,如果matrix[i][j] == 0,则用rowSet和colSet来标记该行列需要置为0。
使用set可以避免重复计算。然后扫描set,将需要置0的修改为0即可。

Java AC

public class Solution {
    public void setZeroes(int[][] matrix) {
        if(matrix == null){
            return;
        }
        int m = matrix.length;
        int n = matrix[0].length;
        Set<Integer> rowSet = new HashSet<Integer>();
        Set<Integer> colSet = new HashSet<Integer>();
        for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				if (matrix[i][j] == 0) {
					rowSet.add(i);
					colSet.add(j);
				}
			}
		}
        for (Integer rowNum : rowSet) {
			for (int i = 0; i < n; i++) {
				matrix[rowNum][i] = 0;
			}
		}
        for (Integer colNum : colSet) {
        	for (int i = 0; i < m; i++) {
				matrix[i][colNum] = 0;
			}
		}
    }
}

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