1615. 最大网络秩

leetcode-1615. 最大网络秩

使用了枚举的办法,时间复杂度\(O(n^2)\)

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
class Solution {
public:
int maximalNetworkRank(int n, vector<vector<int>>& roads) {
vector<vector<int>> rd = vector(n,vector(n,0));
vector<int> roadNum = vector(n,0);
for(vector<int> road : roads)
{
rd[min(road[0],road[1])][max(road[0],road[1])] = 1;
roadNum[road[0]]++;
roadNum[road[1]]++;
}

int maxrank = 0;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++) {
int rank = roadNum[i] + roadNum[j] - rd[i][j];
maxrank = max(maxrank,rank);
}
}

return maxrank;
}
};

也可以用贪心的办法解决,官方题解代码如下:

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
50
51
52
53
54
55
56
class Solution {
public:
int maximalNetworkRank(int n, vector<vector<int>>& roads) {
vector<vector<bool>> connect(n, vector<bool>(n, false));
vector<int> degree(n);
for (auto road : roads) {
int x = road[0], y = road[1];
connect[x][y] = true;
connect[y][x] = true;
degree[x]++;
degree[y]++;
}

int first = -1, second = -2;
vector<int> firstArr, secondArr;
for (int i = 0; i < n; ++i) {
if (degree[i] > first) {
second = first;
secondArr = firstArr;
first = degree[i];
firstArr.clear();
firstArr.emplace_back(i);
} else if (degree[i] == first) {
firstArr.emplace_back(i);
} else if (degree[i] > second){
secondArr.clear();
second = degree[i];
secondArr.emplace_back(i);
} else if (degree[i] == second) {
secondArr.emplace_back(i);
}
}
if (firstArr.size() == 1) {
int u = firstArr[0];
for (int v : secondArr) {
if (!connect[u][v]) {
return first + second;
}
}
return first + second - 1;
} else {
int m = roads.size();
if (firstArr.size() * (firstArr.size() - 1) / 2 > m) {
return first * 2;
}
for (int u: firstArr) {
for (int v: firstArr) {
if (u != v && !connect[u][v]) {
return first * 2;
}
}
}
return first * 2 - 1;
}
}
};

时间复杂度为\(O(m+n)\)