Leecode 685. 冗余连接 II

分类讨论:两种情况,一是有节点有两个父节点,二是头尾相连

 1 struct UnionFind {
 2     vector <int> ancestor;
 3 
 4     UnionFind(int n) {
 5         ancestor.resize(n);
 6         for (int i = 0; i < n; ++i) {
 7             ancestor[i] = i;
 8         }
 9     }
10 
11     int find(int index) {
12         return index == ancestor[index] ? index : ancestor[index] = find(ancestor[index]);
13     }
14 
15     void merge(int u, int v) {
16         ancestor[find(u)] = find(v);
17     }
18 };
19 
20 class Solution {
21 public:
22     vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {
23         int n = edges.size();
24         UnionFind uf = UnionFind(n + 1);
25         auto parent = vector<int>(n + 1);
26         for (int i = 1; i <= n; ++i) {
27             parent[i] = i;
28         }
29         int conflict = -1;
30         int cycle = -1;
31         for (int i = 0; i < n; ++i) {
32             auto edge = edges[i];
33             int node1 = edge[0], node2 = edge[1];
34             if (parent[node2] != node2) {
35                 conflict = i;
36             } else {
37                 parent[node2] = node1;
38                 if (uf.find(node1) == uf.find(node2)) {
39                     cycle = i;
40                 } else {
41                     uf.merge(node1, node2);
42                 }
43             }
44         }
45         if (conflict < 0) {
46             auto redundant = vector<int> {edges[cycle][0], edges[cycle][1]};
47             return redundant;
48         } else {
49             auto conflictEdge = edges[conflict];
50             if (cycle >= 0) {
51                 auto redundant = vector<int> {parent[conflictEdge[1]], conflictEdge[1]};
52                 return redundant;
53             } else {
54                 auto redundant = vector<int> {conflictEdge[0], conflictEdge[1]};
55                 return redundant;
56             }
57         }
58     }
59 };

 

posted on 2024-10-28 14:23  greenofyu  阅读(14)  评论(0编辑  收藏  举报