設置包含0的矩陣 Set Matrix Zeroes

問題:ide

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.idea

Follow up:spa

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?element

解決:it

① 使用一個額外的行和列來標記該行或列是否包含0.io

class Solution {//2ms
    public void setZeroes(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        if(m == 0 || n == 0) return;
        int[] rflag = new int[m];
        int[] lflag = new int[n];
        for (int i = 0;i < m;i ++) {
            for (int j = 0;j < n;j ++) {
                if(matrix[i][j] == 0){
                    rflag[i] = 1;
                    lflag[j] = 1;
                }
            }
        }
        for (int i = 0;i < m ;i ++) {
            for (int j = 0;j < n ;j ++ ) {
                if(rflag[i] == 1 || lflag[j] == 1){
                    matrix[i][j] = 0;
                }
            }
        }
    }
}class

② 使用矩陣的第一行第一列來標記,首先須要先查看第一行第一列的值是否包含0。im

class Solution{ //1ms
    public void setZeroes(int[][] matrix) {
        int m = matrix.length;
        if (m == 0)  return;
        int n = matrix[0].length;
        if (n == 0)  return;
        boolean hasZeroFirstRow = false;
        boolean hasZeroFirstColumn = false;
        // 查看第一列是否包含0
        for (int i = 0; i < m; i ++) {
            if (matrix[i][0] == 0) {
                hasZeroFirstColumn = true;
                break;
            }
        }
        // 查看第一行是否包含0
        for (int j = 0; j < n; j ++) {
            if (matrix[0][j] == 0) {
                hasZeroFirstRow = true;
                break;
            }
        }
        // 使用第一行第一列進行標記
        for (int i = 1; i < m; i ++) {
            for (int j = 1; j < n;j ++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        // 設置除第一行第一列的值
        for (int i = 1; i < m; i ++) {
            for (int j = 1; j < n; j ++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0)  matrix[i][j] = 0;
            }
        }
        // 設置第一行第一列的值
        if (hasZeroFirstColumn) {
            for (int i = 0; i < m; i ++) {
                matrix[i][0] = 0;
            }
        }
        if (hasZeroFirstRow) {
            for (int j = 0; j < n; j ++) {
                matrix[0][j] = 0;
            }
        }
    }
}vi

相關文章
相關標籤/搜索