链接: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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。