73. Set Matrix Zeroes

Description

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

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?

Solution

Iteration

這道題目需要先遍歷一次查找0,利用額外空間去保存某行或某列是否含有0,再遍歷一次將元素修改成0。這樣子呢是O(m + n)的空間復(fù)雜度。
細(xì)細(xì)想來可以利用matrix的第零行和第零列作為標(biāo)記位,這樣額外只需要兩個(gè)變量用于標(biāo)識(shí)第零行和第零列是否有零即可。注意最后修改值的時(shí)候,標(biāo)記位需要最后改才行,否則會(huì)影響其他元素。

class Solution {
    public void setZeroes(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return;
        }
        
        int rows = matrix.length;
        int cols = matrix[0].length;
        boolean firstRowHasZero = false;
        boolean firstColHasZero = false;
        
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                if (i == 0) {
                    firstRowHasZero = firstRowHasZero || matrix[i][j] == 0;
                }
                
                if (j == 0) {
                    firstColHasZero = firstColHasZero || matrix[i][j] == 0;
                }
                
                if (i > 0 && j > 0 && matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        
        for (int i = 1; i < rows; ++i) {
            for (int j = 1; j < cols; ++j) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }
        
        if (firstRowHasZero) {
            for (int i = 0; i < cols; ++i) {
                matrix[0][i] = 0;
            }
        }
        
        if (firstColHasZero) {
            for (int i = 0; i < rows; ++i) {
                matrix[i][0] = 0;
            }
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容