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.lengthnodes, 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:
Input: [4,6,15,35]
Output: 4Example 2:
Input: [20,50,9,63]
Output: 2Example 3:
Input: [2,3,6,7,4,12,21,39]
Output: 82. 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?