1. 程式人生 > >*Leetcode 684. Redundant Connection | Union Find

*Leetcode 684. Redundant Connection | Union Find

https://leetcode.com/problems/redundant-connection/description/

const int SZ = 1005;
int parent[SZ];

int find_parent(int x) {
    return x == parent[x] ? x : find_parent(parent[x]);
}

class Solution {
public:
    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
        vector<int> ret;
        int n = edges.size();
        for (int i = 0; i < n; i++) parent[i] = i;
        for (int i = 0; i < edges.size(); i++) {
            int pa = find_parent(edges[i][0]);
            int pb = find_parent(edges[i][1]);
            if (pa == pb) {
                ret = edges[i];
            } else {
                parent[pb] = pa;
            }
        }
        return ret;
    }
};