Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
[分析]
错误思路:第一遍扫描矩阵,遇到0时将其所在行和列非0元素标记为一个特殊符号。第二遍扫描,将所有特殊符号置0。但因为矩阵元素是整数,找不到不能用整数表示的特殊符号,总有case过不了。
正确的思路是使用两个数组在扫描数组过程中分别存储各行各列是否需要被清零的判断,优化的实现是使用输入矩阵的第一行和第一列进行存储,让matrix[0][0]代表第一行的情况,则还需另一个变量col0存放第一列的状态。第一遍扫描是top-down style,第二遍清零时采用bottom-up style可以让代码更简洁。
[ref]
https://leetcode.com/discuss/15997/any-shortest-o-1-space-solution
解析得比较清楚
http://blog.csdn.net/linhuanmars/article/details/24066199
[url]
public class Solution {
public void setZeroes(int[][] matrix) {
if (matrix == null)
return;
int rows = matrix.length, cols = matrix[0].length;
int col0 = -1;
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0)
col0 = 0;
for (int j = 1; j < cols; j++) {
if (matrix[i][j] == 0)
matrix[i][0] = matrix[0][j] = 0;
}
}
for (int i = rows - 1; i >= 0; i--) {
for (int j = cols - 1; j >= 1; j--) {
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
}
if (col0 == 0)
matrix[i][0] = 0;
}
}
}
[/url]
Leetcode - Set Matrix Zeros
猜你喜欢
转载自likesky3.iteye.com/blog/2236693
今日推荐
周排行