算法 | 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;                 
                       }
                }
           }        
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章