LeetCode 684 冗余连接

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值