树可以看成是一个连通且 无环 的 无向 图。
给定往一棵 n 个节点 (节点值 1~n) 的树中添加一条边后的图。添加的边的两个顶点包含在 1 到 n 中间,且这条附加的边不属于树中已存在的边。图的信息记录于长度为 n 的二维数组 edges ,edges[i] = [ai, bi] 表示图中在 ai 和 bi 之间存在一条边。
请找出一条可以删去的边,删除后可使得剩余部分是一个有着 n 个节点的树。如果有多个答案,则返回数组 edges 中最后出现的边。
示例 1:
输入: edges = [[1,2], [1,3], [2,3]]
输出: [2,3]
示例 2:
输入: edges = [[1,2], [2,3], [3,4], [1,4], [1,5]]
输出: [1,4]
提示:
- n == edges.length
- 3 <= n <= 1000
- edges[i].length == 2
- 1 <= ai < bi <= edges.length
- ai != bi
- edges 中无重复元素
- 给定的图是连通的
分析 这是一套并查集的问题,通过题意得知1,2,3三点相连的情况下会有冗余连接出现,其实就是表示1跟2相连,2跟3相连,这时三个点已经形成一个连通性关系,1跟3再次相连就是冗余的。
所以只要使用并查集,循环将点两两相连,当出现某两个点已经在一个集合中时,该边就是冗余边,题意要求若出现多个答案返回最后出现的边,即我们将答案冗余边覆盖即可。
代码
/**
* @param {number[][]} edges
* @return {number[]}
*/
var findRedundantConnection = function(edges) {
const n = edges.length;
// 题意点从1开始
const set = new UnionSet(n + 1);
let res = ''
for (let i = 0; i < n; i++) {
const data = edges[i];
// 两点不在一个集合中,即两点未连通,将他们连通
if (set.find(data[0]) !== set.find(data[1])) {
set.merge(data[0], data[1])
} else {
// 两点已连通过,这次操作是冗余的
res = data;
}
}
return res
};
/**
* 并查集代码
*/
var UnionSet = function (n) {
this.fathers = new Array(n);
this.size = new Array(n)
for (let i = 0; i < n; i++) {
this.fathers[i] = i
this.size[i] = 1
}
}
UnionSet.prototype.find = function (x) {
if (this.fathers[x] === x) return x;
return this.find(this.fathers[x])
}
UnionSet.prototype.merge = function (a, b) {
const fa = this.find(a), fb = this.find(b);
if (fa === fb) return;
if (this.size[fa] < this.size[fb]) {
this.fathers[fa] = fb
this.size[fb] += this.size[fa]
} else {
this.fathers[fb] = fa
this.size[fa] += this.size[fb]
}
}