js(87)~[684] 冗余连接-并查集

110 阅读1分钟

力扣本题传送门

image.png

这个题,我自己看还是不明白,知道适用并查集,但是不知道怎么用,看完解析,又发现逻辑没有那么复杂,但是我自己就是想不到,关于这个并查集的模版代码,我自己能写出来,就是unite合并这个方法不太理解,其他几个方法都能理解

/*
 * @lc app=leetcode.cn id=684 lang=javascript
 *
 * 
 */

// @lc code=start
/**
 * @param {number[][]} edges
 * @return {number[]}
 */
var findRedundantConnection = function (edges) {
	const uf = new UnionFind(edges.length);
	for (let i = 0; i < edges.length; i++) {
		const edge = edges[i];
		const root1 = uf.find(edge[0]);
		const root2 = uf.find(edge[1]);
		if (root1 === root2) {
			return edge;
		} else {
			uf.unite(root1, root2)
		}

	}
	// 这一步要不要都行
	// return [0]
};
class UnionFind {
	constructor(n) {
		this.parent = new Array(n).fill(0).map((v, i) => i);
		this.size = new Array(n).fill(1);
		this.count = n;
	}
	find(index) {
		let root = this.parent[index];
		if (root != index) {
			root = this.find(root)
		}
		return root
	}
	unite(index1, index2) {
		let root1 = this.find(index1), root2 = this.find(index2)
		if (root1 < root2) {
			[root1, root2] = [root2, root1]
		}
		this.parent[root2] = root1;
		this.size[root1] += this.size[root2];
		this.count--;
	}
	getCount() {
		return this.count;
	}
	connected(index1, index2) {
		return this.find(index1) === this.find(index2)
	}

}
// @lc code=end