Grouping
利用father id判定group
805t. Maximum Association Set
Amazon sells books, every book has books which are strongly associated with it. Given ListA and ListB,indicates that ListA [i] is associated with ListB [i] which represents the book and associated books. Output the largest set associated with each other(output in any sort). You can assume that there is only one of the largest set.
A bookToID map
A ans map
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
Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Return the email in sorted order
An emailToID map
An emailToName map
An ans map
Use EmailToName to update the answer
684. Redundant Connection
Undirect graph, use union- find
685. Redundant Connection II
Direct Graph
1202. Smallest String With Swap
924. Minimize Malware Spread
In a network of nodes, each node i is directly connected to another node j if and only if graph[i][j] = 1. Some nodes initial are initially infected by malware. We will remove one node from the initial list. Return the node that if removed, would minimize the affected nodes
Need to know size of the each init group
If there are 2 inits in group, then it will eventually effected no matter remove any of the node
Update when 1. group size is bigger 2. Same size but with smaller index
Last updated
Was this helpful?