您的位置:首页 > 其它

LeetCode 笔记系列15 Set Matrix Zeroes [稍微有一点hack]

2013-07-14 22:04 399 查看
题目:Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

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?

这个问题使用额外的空间来完成比较直观,但是人要求用“[b]CONSTANT SPACE[/b]” 。。。

我想了半天也没想出来为啥,只有看看leetcode的讨论了。http://discuss.leetcode.com/questions/249/set-matrix-zeroes

其实也不是很难,稍微有点hack。就是首先用两个bool变量记录下第一行和第一列里面是不是有0。接下来利用第一行和第一列保存那些位于[1~m,1~n]范围内的元素的0的位置。就是,如果(i,j)是0,那么我们设置(i,0)(0,j)为0. 所以其实第一行和第一列有点纵横坐标的意思,这样表示待会儿我们要把第i行和第j列都设置成0

public void setZeroes(int[][] matrix) {
int rownum = matrix.length;
if (rownum == 0)  return;
int colnum = matrix[0].length;
if (colnum == 0)  return;

boolean hasZeroFirstRow = false, hasZeroFirstColumn = false;

// Does first row have zero?
for (int j = 0; j < colnum; ++j) {
if (matrix[0][j] == 0) {
hasZeroFirstRow = true;
break;
}
}

// Does first column have zero?
for (int i = 0; i < rownum; ++i) {
if (matrix[i][0] == 0) {
hasZeroFirstColumn = true;
break;
}
}

// find zeroes and store the info in first row and column
for (int i = 1; i < matrix.length; ++i) {
for (int j = 1; j < matrix[0].length; ++j) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}

// set zeroes except the first row and column
for (int i = 1; i < matrix.length; ++i) {
for (int j = 1; j < matrix[0].length; ++j) {
if (matrix[i][0] == 0 || matrix[0][j] == 0)  matrix[i][j] = 0;
}
}

// set zeroes for first row and column if needed
if (hasZeroFirstRow) {
for (int j = 0; j < colnum; ++j) {
matrix[0][j] = 0;
}
}
if (hasZeroFirstColumn) {
for (int i = 0; i < rownum; ++i) {
matrix[i][0] = 0;
}
}
}


View Code
总结下。

这个方法并不是太容易想到。是个算比较hack的方法。当然也算一个技巧了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: