0.并查集实现
class UnionFindSet {
constructor(list) {
this.elementMap = new Map()
this.fatherMap = new Map()
this.sizeMap = new Map()
for (let key of list) {
let ele = this.createElement(key)
this.elementMap.set(key, ele)
this.fatherMap.set(ele, ele)
this.sizeMap.set(ele, 1)
}
}
createElement(value) {
return { value }
}
findHead(ele){
let path = []
while (ele!==this.fatherMap.get(ele)) {
path.push(ele)
ele = this.fatherMap.get(ele)
}
while (path.length) {
this.fatherMap.set(path.pop(),ele)
}
return ele
}
isSameSet(a, b) {
if (this.elementMap.has(a) && this.elementMap.has(b)) {
return this.findHead(this.elementMap.get(a), this.elementMap.get(b))
}
return false
}
union(a, b) {
if (this.elementMap.has(a) && this.elementMap.has(b)) {
let aF = this.findHead(this.elementMap.get(a))
let bF = this.findHead(this.elementMap.get(b))
if (aF !== bF) {
let big = this.sizeMap.get(aF) > this.sizeMap.get(bF) ? aF : bF
let small = big == aF ? bF : aF
this.fatherMap.set(small, big)
this.sizeMap.set(big, this.sizeMap.get(aF) + this.sizeMap.get(bF))
this.sizeMap.delete(small)
}
}
}
}