您的位置:首页 > 其它

LeetCode 73. Set Matrix Zeros(矩阵赋零)

2017-07-24 06:05 429 查看

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?

 

题目标签:Array

 

  这道题目给了我们一个矩阵,让我们把所有是0的位置的那一行和那一列都改成0。我们自己改成0的位置就不需要再改0了。题目还要求我们用 O(1) space,所以就不能另外新建matrix来辅助了。这道题目的难点在于,如果遇到一个0,把它的那一行和那一列都改成0的话,对之后的遍历其他位置的判断就造成了影响。我们可以把这 (遇到0就改这一行和这一列)步骤分解成4个步骤。利用第一行和第一列来存信息,根据信息来对剩下的所有位置改0。那么我们首先要把第一行和第一列里有没有0的这个信息保存起来。   Step 1: 遍历第一行和第一列,设置两个boolean 来保存,如果有0就是true;   Step 2: 遍历剩下的行和列,如果遇到0,就把对应在第一行和第一列里的相对位置改成0;   Step 3: 和step 2一样,遍历除了第一行和第一列的所有位置,对于每一个位置,如果第一行和第一列里的相对位置是0的话,把这个位置改成0;   Step 4: 最后把第一行和第一列也改0,根据开始存的两个boolean 值。      

Java Solution:

Runtime beats 23.97% 

完成日期:07/23/2017

关键词:Array

关键点:把原题给的十字改0的这一个过程分解成四个步骤来实现

 

 

public class Solution
{
public void setZeroes(int[][] matrix)
{
boolean firstRow = false;
boolean firstCol = false;

// iterate the first row and column to see any zeros there
for(int y=0; y<matrix[0].length; y++)
{
if(matrix[0][y] == 0)
{
firstRow = true;
break;
}
}

for(int x=0; x<matrix.length; x++)
{
if(matrix[x][0] == 0)
{
firstCol = true;
break;
}
}

// iterate rest rows and columns,
//if see any zero, put zero in corresponding position in first row and first column
for(int x=1; x<matrix.length; x++) // rows
{
for(int y=1; y<matrix[0].length; y++) // columns
{
if(matrix[x][y] == 0)
{
matrix[x][0] = 0;
matrix[0][y] = 0;
}
}
}

// iterate rest rows and columns again,
// for each position, if corresponding first row or first column has 0, change this to 0
for(int x=1; x<matrix.length; x++)
{
for(int y=1; y<matrix[0].length; y++)
{
if(matrix[x][0] == 0 || matrix[0][y] == 0)
matrix[x][y] = 0;
}
}

// check two boolean firstRow and firstCol, and decide need to make first row and first column to 0
if(firstRow)
for(int y=0; y<matrix[0].length; y++)
matrix[0][y] = 0;

if(firstCol)
for(int x=0; x<matrix.length; x++)
matrix[x][0] = 0;
}
}

参考资料:

http://www.cnblogs.com/grandyang/p/4341590.html

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

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