[路飞][LeetCode]684_冗余连接

84 阅读1分钟

「这是我参与2022首次更文挑战的第11天,活动详情查看:2022首次更文挑战

看一百遍美女,美女也不一定是你的。但你刷一百遍算法,知识就是你的了~~

谁能九层台,不用累土起!

题目地址

题目

树可以看成是一个连通且 无环 的 无向 图。

给定往一棵 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 中无重复元素
  • 给定的图是连通的

解题思路

  • 本题考察的其实还是并查集,我们依旧手写一个并查集
  • 初始化就不多说
  • find:返回能代表i所在集合的节点
  • connect:返回查询的两个下标所在的节点是否连接
  • merge:查询ai 和 bi是否相连,相连返回false,否则将他们相连并返回true

解题代码

var findRedundantConnection = function(edges) {
    const union = new Union(edges.length)
    for(let [a,b] of edges){
        if(!union.merge(a,b)) return [a,b]
    }
};
class Union {
    constructor(n){
        this.arr = new Array(n).fill(0).map((v,i)=>i)
    }

    find(i){ // 
        if(this.arr[i]==i) return i
        return this.find(this.arr[i])
    }

    connect(a,b){ // 判断是否连接
        return this.find(a) == this.find(b)
    }

    merge(a,b){
        if(this.connect(a,b)) return false
        this.arr[this.find(a)] = this.find(b)
        return true
    }
}

如有任何问题或建议,欢迎留言讨论!