Leetcode-set-matrix-zeroes

来源:互联网 发布:网络招聘哪个好 编辑:程序博客网 时间:2024/06/07 03:18

题目描述

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。

因为都是置0,我们在循环查到找到以后,如果直接将所在列和所在行的数全部置0,则继续往后遍历时,算法会分不清0是原来的元素还是更改后的。

所以解决方法是:一开始找到所有的0,把这些值置为Integer.MAX_VALUE-1,然后完成更改,遍历完成后,再把所有的Integer.MAX_VALUE-1变回0。

注意不能使用如下方法:

public class Solution {    public void setZeroes(int[][] matrix) {    int m = matrix.length;    if(m == 0)    return;    int n = matrix[0].length;    int x = Integer.MAX_VALUE - 1;    for(int i=0; i<m; i++){    for(int j=0; j<n; j++){    if(matrix[i][j] == 0){    matrix[i][j] = x;    }    }    }    for(int i=0; i<m; i++){    for(int j=0; j<n; j++){    if(matrix[i][j] == x){       for(int k=0;k<n;k++){                           if(matrix[i][k]!=x)                               matrix[i][k]=0;                       }                       for(int k=0;k<m;k++){                           if(matrix[k][j]!=x)                               matrix[k][j]=0;                       }    }    }    }    for(int i=0; i<m; i++){    for(int j=0; j<n; j++){    if(matrix[i][j] == x){    matrix[i][j] = 0;    }    }    }    }}


0 0