Leetcode1582. 二进制矩阵中的特殊位置

博客探讨了在一个涉及二进制矩阵的编程问题中,使用calloc与malloc的区别。代码示例展示了如何计算特殊位置的数量,并且注意到即使不使用memset初始化,使用calloc也能得到正确结果。问题在于calloc会自动清零分配的内存,而malloc不会,这导致了行为上的不同。

Every day a leetcode

题目来源:1582. 二进制矩阵中的特殊位置

解法

统计每行和以及每列和,分别记为rows,cols

(i,j)为特殊位置的条件:mat[i][j] == 1 && rows[i] == 1 && cols[j] == 1

代码:

int numSpecial(int** mat, int matSize, int* matColSize){
    int m=matSize;
    int n=matColSize[0];
    //int *rows=(int*)calloc(m,sizeof(int));
    //int *cols=(int*)calloc(n,sizeof(int));
    int *rows=(int*)malloc(m*sizeof(int));
    int *cols=(int*)malloc(n*sizeof(int));
    memset(rows,0,sizeof(rows));
    memset(cols,0,sizeof(cols));
    int count=0;

    for(int i=0;i<m;i++)
        for(int j=0;j<n;j++)
        {
            rows[i]+=mat[i][j];
            cols[j]+=mat[i][j];
        }

    for(int i=0;i<m;i++)
        for(int j=0;j<n;j++)
            if(mat[i][j] == 1 && rows[i] == 1 && cols[j] == 1) count++; 

    return count;
}

结果:
在这里插入图片描述

将malloc换成calloc,代码:

int numSpecial(int** mat, int matSize, int* matColSize){
    int m=matSize;
    int n=matColSize[0];
    int *rows=(int*)calloc(m,sizeof(int));
    int *cols=(int*)calloc(n,sizeof(int));
    //int *rows=(int*)malloc(m*sizeof(int));
    //int *cols=(int*)malloc(n*sizeof(int));
    //memset(rows,0,sizeof(rows));
    //memset(cols,0,sizeof(cols));
    int count=0;

    for(int i=0;i<m;i++)
        for(int j=0;j<n;j++)
        {
            rows[i]+=mat[i][j];
            cols[j]+=mat[i][j];
        }

    for(int i=0;i<m;i++)
        for(int j=0;j<n;j++)
            if(mat[i][j] == 1 && rows[i] == 1 && cols[j] == 1) count++; 

    return count;
}

结果:
在这里插入图片描述

为什么calloc行,但malloc不行呢?(这与是否memset无关)

请知道的大神在评论区点拨!

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值