标签:item append def nts account accounts set merge color
代码如下:
class UF(object): def __init__(self,email_lists): self.id={} self.sz={} self.name={} self.emails={} for email,name in email_lists.items(): self.id[email]=email self.sz[email]=1 self.name[email]=name self.emails[email]=set([email]) def root(self,i): while i!=self.id[i]: self.id[i]=self.id[self.id[i]] i=self.id[i] return(i) def connected(self,p,q): return self.root(p)==self.root(q) def union(self,p,q): i=self.root(p) j=self.root(q) if i!=j: if self.sz[i]>self.sz[j]: self.id[j]=i self.sz[i]+=self.sz[j] self.emails[i] |= self.emails[j] else: self.id[i]=j self.sz[j]+=self.sz[i] self.emails[j] |= self.emails[i] class Solution: """ @param accounts: List[List[str]] @return: return a List[List[str]] """ def accountsMerge(self, accounts): # write your code here if len(accounts)<=1: return(accounts) email_lists={} for account in accounts: for i in range(1,len(account)): email_lists[account[i]]=account[0] graph=UF(email_lists) for account in accounts: for i in range(1,len(account)-1): graph.union(account[i],account[i+1]) ans=[] for email in graph.id.keys(): if email==graph.id[email]: #print(graph.emails[email]) #print(list(graph.emails[email])) #print(list(graph.emails[email]).sort()) ans.append([graph.name[email]]+sorted(list(graph.emails[email]))) return(ans)
标签:item append def nts account accounts set merge color
原文地址:https://www.cnblogs.com/Leisgo/p/11857249.html