Skip to content

Add Largest Component Size by Common Factor C# #276

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
public class Solution {
int[] par;
int[] cnt;
public int LargestComponentSize(int[] A) {
var n = A.Length;
par = new int[n];
cnt = new int[n];
var dict = new Dictionary<int, HashSet<int>>();
for(int i=0; i<n; i++){
int d=2, x=A[i];
while(d*d<=x){
if(x%d==0){
while(x%d ==0) x/= d;
if(!dict.ContainsKey(d))
dict.Add(d, new HashSet<int>());
dict[d].Add(i);
}
d++;
}
if(x>1){
if(!dict.ContainsKey(x))
dict.Add(x, new HashSet<int>());
dict[x].Add(i);
}
}

for(int i=0; i<n; i++) par[i] = i;
Array.Fill(cnt, 1);
int max = 1;
foreach(HashSet<int> h in dict.Values){
int fir = h.First();
foreach(var idx in h){
Union(idx, fir);
max = Math.Max(cnt[Find(idx)], max);
}
}
return max;
}
private void Union(int i, int j){
int pi = Find(i);
int pj = Find(j);
if(pi == pj) return ;
par[pi] = pj;
cnt[pj] += cnt[pi];
}

private int Find(int i){
if(i==par[i]) return i;
return par[i] = Find(par[i]);
}
}
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ Solutions in various programming languages are provided. Enjoy it.
27. [Find Right Interval](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/27-Find-Right-Interval)
28. [Implement Rand10() Using Rand7()](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/28-Implement-Rand10()-Using-Rand7())
29. [Pancake Sorting](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/29-Pancake-Sorting)
30. [Largest Component Size by Common Factor](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/30-Largest-Component-Size-by-Common-Factor)

## July LeetCoding Challenge
Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions.
Expand Down