可以用递归或者union set
union set
class Solution {
public int[] findRedundantConnection(int[][] edges) {
int[] us=new int[2000];
for(int i=0;i<2000;i++)
us[i]=i;
for(int[] e:edges) {
if(findSet(e[0], us)==findSet(e[1], us))
return e;
union(e[0],e[1], us);
}
return null;
}
private int findSet(int num, int[] us) {
if(num==us[num]) return num;
while(us[num]!=num)
num=us[num];
return num;
}
private void union(int start, int end, int[] us) {
int startSet = findSet(start, us);
int endSet = findSet(end, us);
if(startSet!=endSet) {
us[startSet]=endSet;
}
}
}
运行结果
递归
class Solution {
Map<Integer, List<Integer>> graph=new HashMap<>();
Set<Integer> allNodes = new HashSet<>();
public int[] findRedundantConnection(int[][] edges) {
for(int[] e: edges) {
if(findPath(e[0], e[1]))
return e;
graph.computeIfAbsent(e[0], k->new ArrayList<>()).add(e[1]);
graph.computeIfAbsent(e[1], k->new ArrayList<>()).add(e[0]);
}
return null;
}
private Boolean findPath(int start, int end) {
if(!graph.containsKey(start)||!graph.containsKey(end)) return false;
for(int i=0; i<graph.get(start).size();i++) {
int curNode = graph.get(start).get(i);
if(allNodes.contains(curNode)) continue;
allNodes.add(curNode);
if(curNode == end) return true;
if(findPath(curNode, end)) return true;
allNodes.remove(curNode);
}
return false;
}
}