Grouping
805t. Maximum Association Set
class UF{
int[] parent;
int[] size;
public UF(int n){
parent = new int[n];
size = new int[n];
for(int i=0; i<n; i++){
parent[i] = i;
size[i] = 1;
}
}
public int find(int x){
if(parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
public void union(int x, int y){
int root_x = find(x);
int root_y = find(y);
if(root_x == root_y) return;
if(size[root_x] < size[root_y]){
parent[root_x] = root_y;
size[root_y] += size[root_x];
}else{
parent[root_y] = root_x;
size[root_x] += size[root_y];
}
}
}
public class Solution {
public List<String> maximumAssociationSet(String[] ListA, String[] ListB) {
UF uf = new UF(5000);
Map<String, Integer> bookToID = new HashMap<>();
int id=0;
for(int i=0; i<ListA.length; i++){
if(!bookToID.containsKey(ListA[i])) bookToID.put(ListA[i], id++);
if(!bookToID.containsKey(ListB[i])) bookToID.put(ListB[i], id++);
uf.union(bookToID.get(ListA[i]), bookToID.get(ListB[i]));
}
Map<Integer, List<String>> ans = new HashMap<>();
for(Map.Entry<String, Integer> entry: bookToID.entrySet()){
int root = uf.find(entry.getValue());
if(!ans.containsKey(root)) ans.put(root, new ArrayList<String>());
ans.get(root).add(entry.getKey());
}
int max=0;
List<String> result = new ArrayList<>();
for(List<String> list: ans.values()){
if(list.size()>max){
max = list.size();
result = list;
}
}
return result;
}
}721. Accounts Merge
684. Redundant Connection
685. Redundant Connection II
924. Minimize Malware Spread
Last updated