2020-08-14

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

题解: 埃氏筛+并查集, 枚举质因子,将拥有相同质因子的数加到同一个集合。

class Solution(object):
    def largestComponentSize(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        cnt = [0]*100001
        MAX = A[0]
        for a in A:
            cnt[a] = 1
            MAX = max(a, MAX)
        MAX+=1

        fa = [i for i in range(0,MAX)]
        def _find(x):
            if fa[x]==x: return x
            fa[x] = _find(fa[x])
            return fa[x]
        
        vis = [0]*MAX
        ans = 1
        for a in range(2,MAX):
            if vis[a]: continue
            vis[a] = 1
            for b in range(2*a,MAX,a):
                if not cnt[b]: continue
                _a = _find(a)
                _b = _find(b)
                if _a == _b: continue
                if cnt[_a] < cnt[_b]: _a,_b = _b, _a
                cnt[_a]+=cnt[_b]
                fa[_b] = _a
                ans = max(ans, cnt[_a])
        
        return ans

 

posted @ 2020-08-14 11:28  樱花庄的龙之介大人  阅读(170)  评论(0编辑  收藏  举报