lintcode 1070 Accounts Merge
Posted leisgo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode 1070 Accounts Merge相关的知识,希望对你有一定的参考价值。
代码如下:
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)
以上是关于lintcode 1070 Accounts Merge的主要内容,如果未能解决你的问题,请参考以下文章
Facebook Graph API me / accounts返回空的Json数据数组