LeetCode·每日一题·1582.二进制矩阵中的特殊位置·模拟

链接:https://leetcode.cn/problems/special-positions-in-a-binary-matrix/solution/-by-xun-ge-v-40wp/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 

题目

 

示例

 

思路

解题思路
【暴力枚举】

题目要统计数组中特殊位置的个数,直接枚举每一个元素的行列进行统计,是否存在多于的1即可

【优化】
上述说到,一个有效的特殊位置,肯定是当前位置为1并且行列也只有一个1存在,那么可以先统计每一行每一列1的个数,然后判断当前位置是否为1在判断行列是否只有一个1即可

代码

int numSpecial(int** mat, int matSize, int* matColSize) {
    int m = matSize, n = matColSize[0];
    int *rowsSum = (int *)malloc(sizeof(int) * m);
    int *colsSum = (int *)malloc(sizeof(int) * n);
    memset(rowsSum, 0, sizeof(int) * m);
    memset(colsSum, 0, sizeof(int) * n);
    for (int i = 0; i < m; i++) {//统计每一行列1的个数
        for (int j = 0; j < n; j++) {
            rowsSum[i] += mat[i][j];
            colsSum[j] += mat[i][j];
        }
    }
    int res = 0;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {//判断当前位置是否为1在判断行列是否只有一个1
            if (mat[i][j] == 1 && rowsSum[i] == 1 && colsSum[j] == 1) {
                res++;
            }
        }
    }
    free(rowsSum);
    free(colsSum);
    return res;
}


作者:xun-ge-v
链接:https://leetcode.cn/problems/special-positions-in-a-binary-matrix/solution/-by-xun-ge-v-40wp/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值