Java Solution, beats 97.15%


  • 0
    B
    class Solution {
        public int[] findRedundantConnection(int[][] edges) {
            int[] union = new int[edges.length + 1];
            for (int i = 0; i < edges.length; i++) {
                int[] edge = edges[i];
                int from = edge[0];
                int to = edge[1];
                int u1 = find(union, from);
                int u2 = find(union, to);
                if (u1 == 0 && u2 == 0) {
                    union[from] = from;
                    union[to] = from;
                } else if (u1 == 0 && u2 != 0) {
                    union[from] = u2;
                } else if (u1 != 0 && u2 == 0) {
                    union[to] = u1;
                } else if (u1 == u2) {
                    return edge;
                } else {
                    union[u1] = u2;
                }
            }
            return null;
        }
    
        int find(int[] union, int index) {
            while (union[index] != index) {
                index = union[index];
            }
            return index;
        }
    }
    

Log in to reply
 

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