Mr-haili / aaa-blog

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

并查集

Mr-haili opened this issue · comments

commented
  1. 是否支持动态添加 vertex ?makeSet(id: string): string 支持我们添加一个新的集合
  2. 动态添加的接口如何命名?makeSet
  3. 如果支持动态添加,如果是已经添加过的怎么办?如果 id 已经存在,那么不做处理。
class UnionFind {
  fa: Record<string, string>;

  constructor(ids: ReadonlyArray<string> = []) {
    this.fa = {};
    ids.forEach(id => this.makeSet(id));
  }

  makeSet(id: string): void {
    if(!this.fa[id]) {
      this.fa[id] = id;
    }
  }

  find(id: string) {
    this.makeSet(id);
    if(this.fa[id] === id) {
      return id;
    }
    return this.fa[id] = this.find(this.fa[id]);;
  }

  union(id1: string, id2: string): void {
    const faId1 = this.find(id1);
    const faId2 = this.find(id2);
    this.fa[faId2] = faId1;
  }

  groupCount(): number {
    return Object.keys(this.fa).filter(id => this.find(id) === id).length;
  }
}