1267. 统计参与通信的服务器
为保证权益,题目请参考 1267. 统计参与通信的服务器(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <set>
#include <vector>
using namespace std;
class Solution {
public:
int countServers(vector<vector<int>> &grid) {
int m = grid.size();
int n = grid[0].size();
vector<set<int>> rowSet(m);
vector<set<int>> colSet(n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
rowSet[i].insert(j);
colSet[j].insert(i);
}
}
}
int ans = 0;
for (int i = 0; i < m; i++) {
if (rowSet[i].size() >= 2) {
ans += rowSet[i].size();
}
}
for (int j = 0; j < n; j++) {
if (colSet[j].size() >= 2) {
ans += colSet[j].size();
for (auto i : colSet[j]) {
if (rowSet[i].size() >= 2) {
ans -= 1;
}
}
}
}
return ans;
}
};
int main() {
Solution so;
vector<vector<int>> grid = {{1, 0}, {0, 1}};
cout << so.countServers(grid) << endl;
return 0;
}
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
39
40
41
42
43
44
45
46
47
48
49
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
39
40
41
42
43
44
45
46
47
48
49