您的位置:首页 > 其它

leetcode--Set Matrix Zeroes

2015-06-08 15:47 489 查看
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?

题意:给定m*n的矩阵,如果某个元素是0,使其同行,同列的所有元素为0

要求使用O(m+n)空间复制度,甚至常数空间

解法1:首先遍历第一行,如果找到0,做标记,说明第一行要清0

遍历第一列,如果找到0,做标记,说明第一列要清0

然后从(1,1)开始遍历矩阵,找到0,将对应的第一行,第一列的元素设置为0,用于标记该行列应该清0

最后,根据第一行,第一列,0的情况,清0

public class Solution {
public void setZeroes(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
boolean firstRow=false,firstCol=false;
for(int i=0;i<rows;i++){
if(matrix[i][0]==0){
firstRow = true;
break;
}
}
for(int i=0;i<cols;i++){
if(matrix[0][i]==0){
firstCol = true;
break;
}
}
for(int i=1;i<rows;i++){
for(int j=1;j<cols;j++){
if(matrix[i][j]==0){
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for(int i=1;i<rows;i++){
if(matrix[i][0]==0){
for(int j=1;j<cols;j++){
matrix[i][j] = 0;
}
}
}
for(int j=1;j<cols;j++){
if(matrix[0][j]==0){
for(int i=1;i<rows;i++){
matrix[i][j] = 0;
}
}
}
if(firstRow) for(int i=0;i<rows;i++) matrix[i][0] = 0;
if(firstCol) for(int j=0;j<cols;j++) matrix[0][j] = 0;
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: