952. 按公因数计算最大组件大小

952. 按公因数计算最大组件大小

两数有共同的大于1的公因数时,就在二者画一条边,问图的最大连通子图的大小。

如果将数的因子作为根节点,把数一个个的挂上去,可以用并查集。

参考自:大佬的题解

class Solution {
	public int largestComponentSize(int[] A) {
		int maxvalue = Integer.MIN_VALUE;
		for (int num : A) // 以数组中最a大的元素为标准开数组
			maxvalue = Math.max(maxvalue, num);
		Check_And_Set cas = new Check_And_Set(maxvalue + 1);

		for (int num : A) {	
			double upBound = Math.sqrt(num);
            //求出每个数的大于1因子,并将数挂到相应的因子根节点上
			for (int i = 2; i <= upBound; i++) {
				if (num % i == 0) {
					cas.union(num, i);
					cas.union(num, num / i);
				}
			}
		}

		// 将候选数组映射成代表元,统计代表元出现的次数,找出最大者
		int[] cnt = new int[maxvalue + 1];
		int res = 0;
		for (int num : A) {
			int root = cas.find(num);	//找到根节点
			cnt[root]++;
			res = Math.max(res, cnt[root]);
		}
		return res;
	}

	class Check_And_Set { // 并查集类
		int[] parent;

		public Check_And_Set(int n) {
			parent = new int[n];
			for (int i = 0; i < n; i++) {
				parent[i] = i;
			}
		}

		// 用递归来找祖先节点
		public int find(int x) {
			while (parent[x] != x) {
				parent[x] = parent[parent[x]];
				x = parent[x];
			}
			return x;
		}

		public void union(int x, int y) {
			int rootX = find(x);
			int rootY = find(y);

			if (rootX != rootY)
				parent[rootX] = rootY;
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值