Set Matrix Zeroes

本文介绍了如何在一个 m x n 的矩阵中,通过一个高效的算法,将元素为零的行和列置零。利用额外的空间进行优化,并详细解释了空间复杂度为 O(m + n) 和常数空间的解决方案。易错点在于在最后将矩阵中的元素置零时,需要正确区分第一行和第一列与其他元素的区别。

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

click to show follow up.

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?

Show Tags

Have you met this question in a real interview? 

思路 : space O(m + n)解法, 设置俩数组 来存储 row  和 column  , 遇到matrix[i][j] == 0  就把 row[i] = true; column[j] = true;

space O(1)  解法, 就是把 第一行 和 第一列当做一个 buffer  来存储 row  和 column

易错点: 最后 改成 0 的时候 ,一定要把 第一行 和 第一列 和 其他的分开来。  先 1 - m ,  1 - n  , 最后再 0行 0 列。

public class Solution {
    public void setZeroes(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        boolean[] row = new boolean[m];
        boolean[] column = new boolean[n];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(matrix[i][j] == 0){
                    row[i] = true;
                    column[j] = true;
                }
            }
        }
        
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(row[i] || column[j])
                    matrix[i][j] = 0;
            }
        }
    }
}


public class Solution {
    public void setZeroes(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        boolean isRow0 = false, isColumn0 = false;
        for(int i = 0; i < m; i++){
            if(matrix[i][0] == 0){
                isColumn0 = true;
                break;
            }
        }
        for(int i = 0; i < n; i++){
            if(matrix[0][i] == 0){
                isRow0 = 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(isColumn0){
            for(int i = 0; i < m; i++)
                    matrix[i][0] = 0;
        }
        if(isRow0){
            for(int i = 0; i < n; i++)
                    matrix[0][i] = 0;
        }
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值