中文描述:
在本问题中, 树指的是一个连通且无环的无向图。
输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, …, N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。
结果图是一个以边组成的二维数组。每一个边的元素是一对[u, v] ,满足 u < v,表示连接顶点u 和v的无向图的边。
返回一条可以删去的边,使得结果图是一个有着N个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边 [u, v] 应满足相同的格式 u < v。
题目描述:
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
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
Note:
The size of the input 2D-array will be between 3 and 1000.
Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.
方法1:
Time complexity:
O
(
N
α
(
N
)
)
≈
O
(
N
)
O(Nα(N))≈O(N)
O(Nα(N))≈O(N),其中 N 为端点数。注意当使用路径压缩(见 find 函数)实现并查集时,单次操作的时间复杂度为
α
(
M
N
)
\alpha(MN)
α(MN),其中
α
(
M
N
)
\alpha(MN)
α(MN)为反阿克曼函数,当自变量 x 的值在人类可观测的范围内(宇宙中粒子的数量)时,函数
α
(
M
N
)
\alpha(MN)
α(MN)的值不会超过 5,因此也可以看成是常数时间复杂度。
Space complexity:
O
(
N
)
O(N)
O(N)
并查集:
标准并查集模版.
树指的是一个连通且无环的无向图
这意味着但我们遍历边的时候发现边时,两个顶点属于相同的连通分量则意味着当前的这条边是多余的。如果两个顶点属于不同的连通分量,则说明在遍历到当前的边之前,这两个顶点之间不连通,因此当前的边不会导致环出现,合并这两个顶点的连通分量。
class Solution {
public int[] findRedundantConnection(int[][] edges) {
int[] res = new int[2];
int n = edges.length;
UnionFind uf = new UnionFind(n+1);
for(int[] e:edges){
int u = e[0];
int v = e[1];
if(uf.find(u) == uf.find(v)){
res[0] = u;
res[1] = v;
}
uf.union(v, u);
}
return res;
}
}
class UnionFind{
int[] father;
UnionFind(int x){
father = new int[x];
for(int i = 0; i < x;i++){
father[i] = i;
}
}
public int find(int x){
if(father[x] != x){
father[x] = find(father[x]);
}
return father[x];
}
public void union(int x, int y){
int fx = find(x);
int fy = find(y);
if(fx != fy){
father[fx] = fy;
}
}
}