Redundant Connection

In this problem, a tree is an undirected graph that is connected and has no cycles.

The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, ..., N), with one additional edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.

The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] with u < v, that represents an undirected edge connecting nodes u and v.

Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v] should be in the same format, with u < v.

Example 1:

Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given undirected graph will be like this:
  1
 / \
2 - 3

思路:union find,先union的edge,father肯定是不一样的,如果后来多一条边,那么father一定相同;T: O(N) S:O(N)

class Solution {
    private class UnionFind {
        private int[] father;
        private int count;
        
        public UnionFind(int n) {
            this.father = new int[n+1];
            for(int i = 0; i < father.length; i++) {
                father[i] = i;
            }
            count = n;
        }
        
        public int find(int x) {
            int j = x;
            while(father[j] != j) {
                j = father[j];
            }
            
            // path compression;
            while(j != x) {
                int fx = father[x];
                father[x] = j;
                x = fx;
            }
            return j;
        }
        
        public void union(int a, int b) {
            int root_a = find(a);
            int root_b = find(b);
            if(root_a != root_b) {
                father[root_a] = root_b;
                count--;
            }
        }
        
        public int getCount() {
            return this.count;
        }
    }
    
    public int[] findRedundantConnection(int[][] edges) {
        if(edges == null || edges.length == 0 || edges[0].length == 0) {
            return new int[0];
        }
        int n = edges.length;
        int[] res = new int[2];
        UnionFind uf = new UnionFind(n);
        for(int i = 0; i < edges.length; i++) {
            int a = edges[i][0];
            int b = edges[i][1];
            int root_a = uf.find(a);
            int root_b = uf.find(b);
            if(root_a == root_b) {
                res[0] = a;
                res[1] = b;
            } else {
                // root_a != root_b;
                uf.union(a, b);
            }
        }
        return res;
    }
}

 

你可能感兴趣的:(Redundant Connection)