Keshawn_lu's Blog

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

字数统计: 337阅读时长: 1 min
2022/09/04 Share

题目简介:

给你一个大小为 rows x cols 的矩阵 mat,其中 mat[i][j]01,请返回 矩阵 *mat* 中特殊位置的数目

特殊位置 定义:如果 mat[i][j] == 1 并且第 i 行和第 j 列中的所有其他元素均为 0(行和列的下标均 从 0 开始 ),则位置 (i, j) 被称为特殊位置。

示例 1:

1
2
3
4
5
6
输入:mat = [[1,0,0],
[0,0,1],
[1,0,0]]

输出:1
解释:(1,2) 是一个特殊位置,因为 mat[1][2] == 1 且所处的行和列上所有其他元素都是 0

提示:

  • rows == mat.length
  • cols == mat[i].length
  • 1 <= rows, cols <= 100
  • mat[i][j]01

思路:

首先记录每行每列中1的个数;

然后再遍历一次数组,当第 i 行第 j1 的个数均为1时,若mat[i][j]也为1,则res++

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
int numSpecial(vector<vector<int>>& mat) {

int res = 0;
vector<int> row(mat.size());
vector<int> col(mat[0].size());

for(int i = 0; i < mat.size(); ++i){

for(int j = 0; j < mat[i].size(); ++j){

if(mat[i][j] == 1){

row[i]++;
col[j]++;
}
}
}

for(int i = 0; i < mat.size(); ++i){

if(row[i] != 1)
continue;

for(int j = 0; j < mat[i].size(); ++j){

if(col[j] == 1 && mat[i][j] == 1){

res++;
break;
}
}
}

return res;
}
};
CATALOG
  1. 1. 题目简介:
  2. 2. 思路:
  3. 3. 代码如下: