并查集
# 概念
# 题目
# LC 0684. 冗余连接
https://leetcode-cn.com/problems/redundant-connection
并查集,只要找到哪条边导致了出现了环
class Solution {
private:
int f[1001];
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
for(int i = 1; i <= 1000; i++) f[i] = i;
for(auto t: edges){
int x = t[0], y = t[1];
if(find(x) != find(y)){
f[find(x)] = find(y);
}else{
return {x, y};
}
}
return {};
}
int find(int x){
return f[x] == x ? x : find(f[x]);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
编辑 (opens new window)
上次更新: 2025/05/21, 06:42:57