952 Largest Component Size by Common Factor
1. Question
Given a non-empty array of unique positive integersA
, consider the following graph:
There are
A.length
nodes, labelledA[0]
toA[A.length - 1];
There is an edge between
A[i]
andA[j]
if and only ifA[i]
andA[j]
share a common factor greater than 1.
Return the size of the largest connected component in the graph.
Example 1:
Example 2:
Example 3:
2. Implementation
(1) Union Find
思路: 对于每个数,我们找出所有它的factor,将它自己与factor通过union-find联合起来, 最后遍历一遍输入数组,通过union-find找到其所属的component,看看哪个component包含输入数组的数字最多即可
3. Time & Space Complexity
Union Find: 时间复杂度O(n * Sqrt(W)), n是输入数组的size,W是输入数组的最大数。空间复杂度O(W)
Last updated
Was this helpful?