[路飞]leetcode-685.冗余连接II

74 阅读1分钟

在本问题中,有根树指满足以下条件的 有向 图。该树只有一个根节点,所有其他节点都是该根节点的后继。该树除了根节点之外的每一个节点都有且只有一个父节点,而根节点没有父节点。

输入一个有向图,该图由一个有着 n 个节点(节点值不重复,从 1 到 n)的树及一条附加的有向边构成。附加的边包含在 1 到 n 中的两个不同顶点间,这条附加的边不属于树中已存在的边。

结果图是一个以边组成的二维数组 edges 。 每个元素是一对 [ui, vi],用以表示 有向 图中连接顶点 ui 和顶点 vi 的边,其中 ui 是 vi 的一个父节点。

返回一条能删除的边,使得剩下的图是有 n 个节点的有根树。若有多个答案,返回最后出现在给定二维数组的答案。力扣原文

 

示例 1:

输入: edges = [[1,2],[1,3],[2,3]]
输出: [2,3]

示例 2:

输入: edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]
输出: [4,1]

  解题:

 class UnionFind {
    constructor(length) {
      this.parent = new Array(length).fill(0).map((v, j) => j);
      this.rank = new Array(length).fill(1);
      this.setCount = length;
    }
    findSet(index) {
      if (this.parent[index] !== index) {
        this.parent[index] = this.findSet(this.parent[index]);
      }
      return this.parent[index];
    }
    unite(indei, index2) {
      let root1 = this.findSet(indei),
        root2 = this.findSet(index2);
      if (root1 !== root2) {
        if (this.rank[root1] < this.rank[root2]) {
          [root1, root2] = [root2, root1];
        }
        this.parent[root2] = root1;
        this.rank[root1] += this.rank[root2];
        this.setCount--;
      }
    }
    getCount() {
      return this.setCount;
    }
  }
var findRedundantDirectedConnection = function(edges) {
    const len=edges.length
    const uf=new UnionFind(len+1)
    const parent = [];
    let conflict=-1,cycle=-1;
    for(let i = 1;i<=(len +1);i++){
        parent[i] = i; //做一个初始化 
    }
    for ( i in edges) {
        let edge = edges[i]
        let node1 = edge[0],node2 = edge[1];
       if(parent[node2]!=node2){
        conflict=i
       }else{
           parent[node2]=node1
           if(uf.findSet(node1)==uf.findSet(node2)){
            cycle=i
           }else{
               uf.unite(node1,node2)
           }
       }
    }
    if(conflict<0){
        return edges[cycle]
    }else{
        const  conflictNode=edges[conflict]
        if(cycle >= 0){
            return [parent[conflictNode[1]],conflictNode[1]]
        }else {
            return conflictNode
        }
    }

};