LeetCode 684 冗余连接
题目描述:
在本问题中, 树指的是一个连通且无环的无向图。
输入一个图,该图由一个有着N
个节点 (节点值不重复1, 2, ..., N
) 的树及一条附加的边构成。附加的边的两个顶点包含在1
到N
中间,这条附加的边不属于树中已存在的边。
结果图是一个以边组成的二维数组。每一个边的元素是一对[u, v]
,满足 u < v
,表示连接顶点u
和v
的无向图的边。
返回一条可以删去的边,使得结果图是一个有着N
个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边 [u, v]
应满足相同的格式 u < v
。
并查集
按照edges中的顺序对边进行遍历并建立并查集,返回第一次出现环的边(唯一)
执行用时:1 ms, 在所有 Java 提交中击败了97.15%的用户
内存消耗:40 MB, 在所有 Java 提交中击败了68.88%的用户
class Solution {
public int[] findRedundantConnection(int[][] edges) {
//按edges中的顺序建立连通图,返回第一次出现环时的边
int[] result = null;
int[] nodes = new int[edges.length+1];
Arrays.fill(nodes, -1);
for(int[] edge: edges) {
if(!union(edge[0], edge[1], nodes)) {
result = edge;
}
}
return result;
}
public int findRoot(int x, int[] nodes) {
while(nodes[x]!=-1) {
x = nodes[x];
}
return x;
}
public boolean union(int x, int y, int[] nodes) {
int rootX = findRoot(x, nodes);
int rootY = findRoot(y, nodes);
if(rootX==rootY) {
return false;
}
nodes[rootX] = rootY;
return true;
}
}