Java implementation LeetCode 73 matrix to zero

73. Matrix Zero

Given an mxn matrix, if one element is zero, then all elements of its row and column are set to 0. Use the in-place algorithm.

Example 1:

Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[0 , 1]
]
example 2:

Input:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
Output:
[
[0,0,0,0],
[0,4 , 5,0],
[0,3,1,0]
]
Advanced:

A direct solution is to use O (mn) additional space, but this is not a good solution.
A simple improvement is to use O (m + n) additional space, but this is still not the best solution.
Can you think of a solution constant space it?

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/set-matrix-zeroes
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

class Solution {
    public void setZeroes(int[][] matrix) { 
          int[] xNum = new int[matrix[0].length];
        int[] yNum = new int[matrix.length];
        for(int i=0;i<matrix.length;i++){
            for(int j=0;j<matrix[i].length;j++){
                if(matrix[i][j]==0) {
                    xNum[j] = 1;
                    yNum[i] = 1;
                }
            }
        }

        for(int i=0;i<matrix.length;i++){
            for(int j=0;j<matrix[i].length;j++){
                if(xNum[j]==1||yNum[i]==1){
                    matrix[i][j] = 0;
                }
            }
        }
        
    }
}
发布了1189 篇原创文章 · 获赞 1万+ · 访问量 54万+

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104343739