(解题思路很trick)LeetCode#73. Set Matrix Zeroes

  • 题目:输入一个二维数组matrix,如果matrix[i][j]为0,则将第i行和第j列的元素都设置为0
  • 难度:Medium
  • 思路:利用两个变量判断第0行和第0列本身是否需要设置为0,然后用数组中的第0行和第0列来存储第i行或者第j列需要设置为0
  • 代码:
    来自Discuss里的思路

     // Use first row and first column as markers. 
    // if matrix[i][j] = 0, mark respected row and col marker = 0; indicating
       that later this respective row and col must be marked 0;
    // And because you are altering first row and collumn, 
       you need to  have two variables to track their own status. 
    // So, for ex, if any one of the first row is 0, fr = 0, 
       and at the end set all first row to 0;
    
public 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;
        //因为将第i行或者第i列是否为需要设置0的标志用第0行或者第0列中的元素来标志,
        //所以需要额外判断第0行或者第0列是否需要设置为0
        boolean rf = false;//标志第0行是否全为0
        boolean cf = false;//标志第0列是否全为0
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < cols; j++){
                if(matrix[i][j] == 0){
                    if(i == 0){
                        rf = true;
                    }
                    if(j == 0){
                        cf = true;
                    }
                    matrix[0][j] = 0;
                    matrix[i][0] = 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(rf){
            for(int i = 0; i < cols; i++){
                matrix[0][i] = 0;
            }
        }
        if(cf){
            for(int i = 0; i < rows; i++){
                matrix[i][0] = 0;
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值