跳至主要內容

73. 矩阵置零

T4mako算法哈希表数组矩阵小于 1 分钟

73. 矩阵置零

中等

题目描述open in new window

解法思路:首先通过遍历记录哪些行和列需要置 0,再遍历一次将 0 填充

class Solution {
    public void setZeroes(int[][] matrix) {
		HashSet<Integer> rows = new HashSet<>();
		HashSet<Integer> cols = new HashSet<>();
		for (int r = 0; r < matrix.length; r++) {
			for (int c = 0; c < matrix[0].length; c++) {
				if (matrix[r][c] == 0) {
					rows.add(r);
					cols.add(c);
				}
			}
		}
		for (int r = 0; r < matrix.length; r++) {
			for (int c = 0; c < matrix[0].length; c++) {
				if (rows.contains(r)) {
					matrix[r][c] = 0;
				}
				if (cols.contains(c)) {
					matrix[r][c] = 0;
				}
			}
		}

	}
}
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.5