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无关)
请知道的大神在评论区点拨!
博客探讨了在一个涉及二进制矩阵的编程问题中,使用calloc与malloc的区别。代码示例展示了如何计算特殊位置的数量,并且注意到即使不使用memset初始化,使用calloc也能得到正确结果。问题在于calloc会自动清零分配的内存,而malloc不会,这导致了行为上的不同。
299

被折叠的 条评论
为什么被折叠?



