684. 冗余连接
1 class UnionFind 2 { 3 public: 4 vector<int> parent; // 存储若干棵树 5 int count; 6 UnionFind(int n) 7 { 8 count = n; 9 for (int i = 0; i < n; i++) parent.push_back(i); 10 } 11 /* 返回节点 x 的根节点 */ 12 int Find(int x) 13 { 14 // 进行路径压缩 15 if (parent[x] != x) parent[x] = Find(parent[x]); 16 return parent[x]; 17 } 18 void Union(int p, int q) 19 { 20 int rootP = Find(p); 21 int rootQ = Find(q); 22 if (rootP == rootQ) return; 23 24 parent[rootQ] = rootP; 25 count--; 26 } 27 }; 28 29 class Solution 30 { 31 public: 32 vector<int> findRedundantConnection(vector<vector<int>>& edges) 33 { 34 if(edges.empty() || edges[0].empty()) return {}; 35 int n = edges.size(); 36 UnionFind uf(n + 1); 37 for(auto e : edges) 38 { 39 int a = e[0],b = e[1]; 40 if(uf.Find(a) == uf.Find(b)) return {a,b}; 41 uf.Union(a,b); 42 } 43 return {}; 44 } 45 };
Mamba never out

浙公网安备 33010602011771号