您的位置:首页 > 其它

[leetcode]Set Matrix Zeroes

2014-07-17 16:56 176 查看

Set Matrix Zeroes

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?

这道题前天实验室同学问过我,今天简单整理一下四种空间复杂度的解法,时间复杂度肯定是一样的O(mn)

算法:

思路1. 空间复杂度O(mn)

开辟O(m*n)空间tag,标记matrix中每个0的位置,全部标记完之后,再遍历tag,将matrix相关行列赋0

public class Solution {
public void setZeroes(int[][] matrix) {
if(matrix == null || matrix.length == 0) return;
int height = matrix.length;
int width = matrix[0].length;
boolean hasZeroInFirstRow = false;
for(int j = 0; j < width; j++){
if(matrix[0][j] == 0)
hasZeroInFirstRow = true;
}
for(int i = 1; i < height; i++){
boolean hasZero = false;
for(int j = 0; j < width; j++){
if(matrix[i][j] == 0){
hasZero = true;
matrix[0][j] = 0;
}
}
if(hasZero)
for(int j = 0; j < width; matrix[i][j++] = 0);
}
for(int j = 0; j < width; j++){
if(matrix[0][j] == 0){
for(int i = 0; i < height; matrix[i++][j] = 0);
}
}
if(hasZeroInFirstRow)
for(int j = 0; j < width; matrix[0][j++] = 0);
}
}


View Code

以上四种算法的时间复杂度都是O(m*n),空间复杂度从O(m*n)到O(1),可能代码写的不够简洁,但是可读性应该还好吧,哈哈。FYI
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: