算法 | Leetcode 面试题 01.08. 零矩阵

编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。

示例 1:

输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]

示例 2:

输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]

题解:
class Solution {
    public void setZeroes(int[][] matrix) {
        int lenx = matrix.length, leny = matrix[0].length;
        boolean[] row = new boolean[lenx],col = new boolean[leny];
        for(int i = 0;i<lenx;i++){
            for(int j=0;j<leny;j++){
                if(matrix[i][j]==0){
                    row[i] = true;
                    col[j] = true;
                }
            }
        }
        for(int i=0;i<lenx;i++){
              for(int j=0;j<leny;j++){
                if(row[i]||col[j]){
                    matrix[i][j]=0;                 
                       }
                }
           }        
    }
}

猜你喜欢

转载自blog.csdn.net/CYK5201995/article/details/106408410
今日推荐