LeetCode_OJ【73】Set Matrix Zeroes

来源:互联网 发布:手机短信淘宝链接 编辑:程序博客网 时间:2024/05/16 19:03

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?

给定一个矩阵,如果矩阵中某个元素为0,则与该元素同行同列的元素都将置为0. 要求算法位原地算法(空间复杂度为O(1)).

按照提示,一开始可以复制一个矩阵,对照复制的矩阵的每个元素对原来的矩阵进行操作,但是这样需要O(mn)的额外空间。

然后想到只需要记录哪些行和列需要置0,先遍历一遍矩阵,得到需要置0的行和列,然后再对矩阵进行操作,这样需要O(m + n)的空间记录这些行和列。

仔细想一下,其实这些信息可以直接记录在矩阵的第一行和第一列。先遍历一遍矩阵,如果i行需要置0,则设置matrix[i][0]为0,如果j列需要置0,则matrix[0][j]为0.

然后根据第一行第一列再对矩阵操作。

不过在实现这个思路的时候需要小心。

首先,需要两个额外空间记录第一行和第一列是否需要置0;

由于其他行和列在置0的时候,需要参照第一行第一列,所以第一行第一列在其他行列重置时不能改变。

处理完其他行列后再根据设置的两个额外空间处理第一行第一列。

JAVA实现如下:

public class Solution {    public void setZeroes(int[][] matrix) {        int x = 1 , y = 1;        //看第一行和第一列是否出现值为0的元素        for(int i = 0 ; i < matrix.length ; i ++)            if(matrix[i][0] == 0)                y = 0;        for(int j = 0 ; j < matrix[0].length ; j ++)            if(matrix[0][j] == 0)                x = 0;        //遍历其他行和列,并将信息记录在第一行第一列for(int i = 1 ; i < matrix.length ; i ++){for(int j = 1 ; j < matrix[0].length ; j ++ ){if(matrix[i][j] == 0){matrix[i][0] = 0;matrix[0][j] = 0;}}}//根据第一行第一列的值是否为0,将矩阵其他行其他列的元素置0for(int i = 1 ; i < matrix.length ; i ++){for(int j = 1 ; j < matrix[0].length ; j ++ ){if(matrix[i][0] == 0 || matrix[0][j] == 0){matrix[i][j] = 0;}}}//设置第一行和第一列。if(x == 0)    for(int j = 0 ; j < matrix[0].length ; j ++)        matrix[0][j] = 0;if(y == 0)    for(int i = 0 ; i < matrix.length ; i ++)                matrix[i][0] = 0;    }}


0 0
原创粉丝点击