LeetCode | Set Matrix Zeroes

2014-11-24 10:42:41 · 作者: · 浏览: 1

题目

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.

Follow up:

Did you use extra space
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution

分析

题目要求使用常数的额外空间,因此需要借助矩阵本身的空间来辅助存储,这里借用了矩阵的第一行和第一列来辅助纪录该行或该列是否为0.由于第一行第一列自身发生了改变,再用两个布尔变量纪录第一行和第一列是否为0即可。

代码

public class SetMatrixZeroes {
	public void setZeroes(int[][] matrix) {
		if (matrix == null || matrix.length == 0) {
			return;
		}
		int M = matrix.length;
		int N = matrix[0].length;
		boolean isFirstRowZero = false;
		boolean isFirstColumnZero = false;
		for (int j = 0; j < N; ++j) {
			if (matrix[0][j] == 0) {
				isFirstRowZero = true;
				break;
			}
		}
		for (int i = 0; i < M; ++i) {
			if (matrix[i][0] == 0) {
				isFirstColumnZero = true;
				break;
			}
		}
		for (int i = 1; i < M; ++i) {
			for (int j = 1; j < N; ++j) {
				if (matrix[i][j] == 0) {
					matrix[i][0] = 0;
					matrix[0][j] = 0;
				}
			}
		}

		for (int i = 1; i < M; ++i) {
			for (int j = 1; j < N; ++j) {
				if (matrix[i][0] == 0 || matrix[0][j] == 0)
					matrix[i][j] = 0;
			}
		}

		if (isFirstRowZero) {
			for (int j = 0; j < N; ++j) {
				matrix[0][j] = 0;
			}
		}

		if (isFirstColumnZero) {
			for (int i = 0; i < M; ++i) {
				matrix[i][0] = 0;
			}
		}
	}
}