题目地址:
https://leetcode.com/problems/special-positions-in-a-binary-matrix/
给定一个 m × n m\times n m×n的 0 − 1 0-1 0−1矩阵,判断其有多少个 1 1 1满足其是它所在行和列里的唯一的 1 1 1。
先统计每行和每列总共多少个 1 1 1,然后搜索所有的 1 1 1看它是否是本行、列里唯一的 1 1 1。代码如下:
public class Solution {
public int numSpecial(int[][] mat) {
int[] row1 = new int[mat.length], col1 = new int[mat[0].length];
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[0].length; j++) {
if (mat[i][j] == 1) {
row1[i]++;
col1[j]++;
}
}
}
int res = 0;
for (int i = 0; i < mat.length; i++) {
if (row1[i] != 1) {
continue;
}
for (int j = 0; j < mat[0].length; j++) {
if (col1[j] != 1) {
continue;
}
if (mat[i][j] == 1) {
res++;
}
}
}
return res;
}
}
时间复杂度 O ( m n ) O(mn) O(mn),空间 O ( m + n ) O(m+n) O(m+n)。