LeetCode-Redundant Connection

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83624703

一、Description

题目描述:给定一个二维数组,分别代表一个无向图的一条边,从数组中去掉一条边,使得该图可以成为一棵树(无回路),如果有多个答案,返回数组中靠后的那条边。

Example 1:

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

Example 2:

Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]
Output: [1,4]
Explanation: The given undirected graph will be like this:
5 - 1 - 2
    |   |
    4 - 3

二、Analyzation

这个题其实跟树没有太大关系,刚开始一直想着用邻接矩阵存边,再怎么遍历到每个点,后来觉得想复杂了,直接用并查集求是否连通即可。从开始遍历数组,每次访问一条边<u, v>,先判断u和v是否连通,如果不连通就join这两个点,否则说明当前边是重复的,就返回当前的这两个点new int[]{u, v}。

关于并查集的讲解,可以看我这篇文章:并查集详解,图解讲得很详细。


三、Accepted code

class Solution {
    int[] pre;
    public int[] findRedundantConnection(int[][] edges) {
        if (edges == null) {
            return new int[2];
        }
        int n = edges.length;
        pre = new int[n + 1];
        for (int i = 0; i < n; i++) {
            pre[i] = i;
        }
        for (int i = 0; i < n; i++) {
            int u = edges[i][0];
            int v = edges[i][1];
            int fx = Find(u), fy = Find(v);
            if (fx != fy) {
                pre[fy] = fx;
            } else {
                return new int[]{u, v};
            }
        }
        return new int[2];
    }
    public int Find(int x) {
        int r = x;  
        while (r != pre[r])  
            r = pre[r];  
        int i = x, j;  
        while (pre[i] != r)  
        {  
            j = pre[i];  
            pre[i] = r;  
            i = j;  
        }  
        return r;
    }
    
}

猜你喜欢

转载自blog.csdn.net/Apple_hzc/article/details/83624703