您的位置:首页 > 其它

个人记录-LeetCode 73. Set Matrix Zeroes

2017-01-06 20:16 302 查看
问题:

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?

代码示例:

1、整体思路其实就是先标记后处理,使用的是O(m + n) space。

public class Solution {
public void setZeroes(int[][] matrix) {
if (matrix == null || matrix.length < 1 || matrix[0].length < 1) {
return;
}

int rowNum = matrix.length;
int colNum = matrix[0].length;

Set<Integer> rowSet = new HashSet<>();
Set<Integer> colSet = new HashSet<>();

//记录将被清零的行和列
for (int i = 0; i < rowNum; ++i) {
for (int j = 0; j < colNum; ++j) {
if (matrix[i][j] == 0) {
rowSet.add(i);
colSet.add(j);
}
}
}

//执行清零操作
for (int i = 0; i < rowNum; ++i) {
if (rowSet.contains(i)) {
for (int j = 0; j < colNum; ++j) {
matrix[i][j] = 0;
}
}
}

for (int j = 0; j < colNum; ++j) {
if (colSet.contains(j)) {
for (int i = 0; i < rowNum; ++i) {
matrix[i][j] = 0;
}
}
}
}
}


2、使用constant space,本质还是先标记后处理,不过是将标记信息写入到第一行和第一列。

public class Solution {
public void setZeroes(int[][] matrix) {
if (matrix == null || matrix.length < 1 || matrix[0].length < 1) {
return;
}

int rowNum = matrix.length;
int colNum = matrix[0].length;

//先单独标记第一列
boolean firstColHasZero = false;
for (int i = 0; i < rowNum; ++i) {
if (matrix[i][0] == 0) {
firstColHasZero = true;
break;
}
}

//先单独标记第一行
boolean firstRowHasZero = false;
for (int j = 0; j < colNum; ++j) {
if (matrix[0][j] == 0) {
firstRowHasZero = true;
break;
}
}

//其它标记写入第一行和第一列
for (int i = 1; i < rowNum; ++i) {
for (int j = 1; j < colNum; ++j) {
if (matrix[i][j] == 0) {
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}

//处理普通的行列
for (int i = 1; i < rowNum; ++i) {
if (matrix[i][0] == 0) {
for (int j = 0; j < colNum; ++j) {
matrix[i][j] = 0;
}
}
}

for (int j = 1; j < colNum; ++j) {
if (matrix[0][j] == 0) {
for (int i = 0; i < rowNum; ++i) {
matrix[i][j] = 0;
}
}
}

//最后单独处理第一行和第一列
if (firstRowHasZero) {
for (int j = 0; j < colNum; ++j) {
matrix[0][j] = 0;
}
}

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


节省了空间,但写法变得不够直观,从代码可读性来讲,刻意这么做没有什么意义。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: