Union-Find Method (beats 94%)


  • 0
    class Solution {
    public:
       bool validTree(int n, vector<pair<int, int>>& edges) {
            vector<int> group(n, 0);
            iota(group.begin(), group.end(), 0);
            for(auto i:edges) {
                int u = i.first;
                int v = i.second;
                while(u!=group[u]) u = group[u];
                while(v!=group[v]) v = group[v];
                if(v==u) return false;
                group[u] = v;
                n--;
            }
            return n==1;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.