首页 > 其他 > 详细

LeetCode | Set Matrix Zeroes

时间:2014-03-15 00:39:27      阅读:500      评论:0      收藏:0      [点我收藏+]

题目

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;
			}
		}
	}
}


LeetCode | Set Matrix Zeroes,布布扣,bubuko.com

LeetCode | Set Matrix Zeroes

原文:http://blog.csdn.net/perfect8886/article/details/21252817

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!