码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode 1070 Accounts Merge

时间:2019-11-14 15:18:01      阅读:75      评论:0      收藏:0      [点我收藏+]

标签: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)

 

lintcode 1070 Accounts Merge

标签:item   append   def   nts   account   accounts   set   merge   color   

原文地址:https://www.cnblogs.com/Leisgo/p/11857249.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!