LeetCode 684 冗余连接
题目:中等
思路:涉及到图论,想到并查集
具体的,初始时,每个节点都属于不同集合,遍历每一条边,判断这条边所连接的两个顶点是否属于同一集合
- 若不属于同一集合,则说明在遍历到当前边之前,两节点不连通,因此当前边不会导致环出现,进而将两个点合并为一个集合。
- 若属于同一集合,则说明在遍历到当前边之前,两节点已经连通,因此当前边会导致环出现,此时应将当前边作为结果返回。
class Solution{
public static class Element{
public int value;
public Element(int value){
this.value = value;
}
}
public static class UnionFindSet{
public HashMap<Integer,Element> elementMap;
public HashMap<Element,Element> fatherMap;
public HashMap<Element,Integer> sizeMap;
public HashSet<Integer> set;
public UnionFindSet(int[][] arr){
elementMap = new HashMap<>();
fatherMap = new HashMap<>();
sizeMap = new HashMap<>();
set = new HashSet<>();
int i,j;
for(i = 0;i<arr.length;i++){
for(j = 0;j<2;j++){
if(!set.contains(arr[i][j])){
set.add(arr[i][j]);
Element element = new Element(arr[i][j]);
elementMap.put(arr[i][j],element);
fatherMap.put(element,element);
sizeMap.put(element,1);
}
}
}
}
private Element findFather(Element element){
Stack<Element> stack = new Stack<>();
while(element != fatherMap.get(element)){
stack.add(element);
element = fatherMap.get(element);
}
while(!stack.isEmpty()){
fatherMap.put(stack.pop(),element);
}
return element;
}
public boolean isSameSet(int a,int b){
if(elementMap.containsKey(a) && elementMap.containsKey(b)){
return findFather(elementMap.get(a)) == findFather(elementMap.get(b));
}
return false;
}
public void union(int a,int b){
if(elementMap.containsKey(a) && elementMap.containsKey(b)){
Element aF = findFather(elementMap.get(a));
Element bF = findFather(elementMap.get(b));
if(aF != bF){
Element big = sizeMap.get(aF)>=sizeMap.get(bF)?aF:bF;
Element small = big == aF?bF:aF;
fatherMap.put(small,big);
sizeMap.put(big,sizeMap.get(big)+sizeMap.get(small));
}
}
}
}
public int[] findRedundantConnection(int[][] edges){
Solution.UnionFindSet ufSet = new Solution.UnionFindSet(edges);
int i;
for(i = 0;i<edges.length;i++){
int[] temp = edges[i];
if(ufSet.isSameSet(temp[0],temp[1])) return temp;
else ufSet.union(temp[0],temp[1]);
}
return new int[]{0,0};
}
}
链接:https://leetcode-cn.com/problems/redundant-connection/