Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

并查集 #151

Open
TieMuZhen opened this issue Apr 4, 2022 · 0 comments
Open

并查集 #151

TieMuZhen opened this issue Apr 4, 2022 · 0 comments
Labels

Comments

@TieMuZhen
Copy link
Owner

前言

首先要知道并查集可以解决什么问题呢?

主要就是集合问题,两个节点在不在一个集合,也可以将两个节点添加到一个集合中。

题目

LeetCode 684
image
image

/**
 * @param {number[][]} edges
 * @return {number[]}
 */

var findRedundantConnection = function(edges) {
    let parents = new Array(edges.length + 1);
    // 并查集初始化
    for(let i = 0; i < edges.length + 1; i++){
        parents[i] = i;
    }
    // 并查集里寻根的过程
    var find = function(n) {
        if(n != parents[n]){
            return parents[n] = find(parents[n]);
        }
        return n;
    }

    // 将a->b 这条边加入并查集
    var join = function(a, b){
        let p1 = find(a);
        let p2 = find(b);
        if(p1 != p2){
            parents[p1] = p2;
        }
    }
    // 判断 u 和 v是否找到同一个根
    var same = function(a, b){
        let p1 = find(a);
        let p2 = find(b);
        return p1 == p2;
    }
    for(let i = 0; i < edges.length; i++){
        if(same(edges[i][0], edges[i][1])){
            return edges[i];
        }else{
            join(edges[i][0], edges[i][1]);
        }
    }
    return [];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant