1.题目
LeetCode: 684. 冗余连接
【medium】
2.解题
方法一:并查集
参考:
https://leetcode-cn.com/problems/redundant-connection/solution/rong-yu-lian-jie-by-leetcode-solution-pks2/
java:
class Solution {
public int[] findRedundantConnection(int[][] edges) {
int count = edges.length;
int[] parent = new int[count + 1];
for (int i = 1; i <= count; i++) {
parent[i] = i;
}
for (int i = 0; i < count; i++) {
int[] edge = edges[i];
int node1 = find(parent, edge[0]), node2 = find(parent, edge[1]);
if (node1 != node2) {
parent[node1] = node2;
} else {
return edge;
}
}
return new int[0];
}
public int find(int[] parent, int index) {
if (parent[index] != index) {
parent[index] = find(parent, parent[index]);
}
return parent[index];
}
}
3.相关知识
3.1 并查集
https://zhuanlan.zhihu.com/p/93647900/