LeetCode——冗余连接

Q:在本问题中, 树指的是一个连通且无环的无向图。
输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, ..., N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。
结果图是一个以边组成的二维数组。每一个边的元素是一对[u, v] ,满足 u < v,表示连接顶点u 和v的无向图的边。
返回一条可以删去的边,使得结果图是一个有着N个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边 [u, v] 应满足相同的格式 u < v。

示例 1:
输入: [[1,2], [1,3], [2,3]]
输出: [2,3]
解释: 给定的无向图为:
1
/ \
2 - 3
示例 2:
输入: [[1,2], [2,3], [3,4], [1,4], [1,5]]
输出: [1,4]
解释: 给定的无向图为:
5 - 1 - 2
      |    |
  4 - 3
注意:
输入的二维数组大小在 3 到 1000。
二维数组中的整数在1到N之间,其中N是输入数组的大小。

A:

典型的并查集问题

并查集类:

 1 public class Union {
 2     int count;//树的个数
 3     int[] root;//每个点的根节点
 4     int[] size;//一棵树的节点数
 5 
 6     Union(int m) {
 7         root = new int[m];
 8         size = new int[m];
 9         for (int i = 0; i < m; i++) {
10             root[i] = i;//初始点,每个点的根节点都是自己
11             size[i] = 1;//每棵树只有1个节点
12         }
13         count = m;//总共有m棵树
14     }
15 
16     public void unionF(int i, int j) {
17         int x = find(i);//i的根节点
18         int y = find(j);//j的根节点
19         if (x != y) {
20             if (size[x] > size[y]) {//x树更大,把y接上去
21                 root[y] = x;
22                 size[y] += size[x];
23             } else {//y树更大,把x接上去
24                 root[x] = y;
25                 size[x] += size[y];
26             }
27             count--;
28         }
29     }
30 
31     public int find(int j) {
32         while (root[j] != j) {
33             //这句是为了压缩路径,不要的话可以跑的通,但效率变低
34             root[j] = root[root[j]];
35             j = root[j];
36         }
37         return j;
38     }
39 
40     public int count() {
41         return count;
42     }
43 
44     public boolean connected(int i, int j) {
45         int x = find(i);
46         int y = find(j);
47         return x == y;
48     }
49 }

代码:

 1     public int[] findRedundantConnection(int[][] edges) {
 2         int num = edges.length;
 3         Union u = new Union(num);
 4         for (int[] edge : edges) {
 5             if (u.connected(edge[0] - 1, edge[1] - 1))
 6                 return edge;
 7             u.unionF(edge[0] - 1, edge[1] - 1);
 8         }
 9         return new int[]{};
10     }

猜你喜欢

转载自www.cnblogs.com/xym4869/p/12736920.html