goodwish

1070. Accounts Merge

Nov 3rd, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.06 KB | None | 0 0
  1. way 1a, email 作为节点, 做 union().
  2.  
  3. 每个邮件数组, 所有邮件都和第一个邮件 union(), 合并社团.
  4. 把所有的邮件再 find() 一遍, father 压缩成一层, 确保小弟直接汇报给一个老大.
  5. - 也可以找每个 mail 的老大, mail 逐个加进老大一组,
  6. - for mail in mails: parent = find(mail); parent_child_mails[parent].append(mail);
  7. 生成结果,
  8. 根据 parent_mail, 从 mail_name 中, 找到 user_name,
  9. parent_child_mails[parent_mail] = child mails list, 一个老大带小弟们生成一行.
  10.  
  11. 数据结构:
  12. father[node] = 老大, hashmap, 每个节点的老大.
  13. mail_name[mail] = name, hashmap 记录邮件和人名的关系.
  14. parent_child_mails[parent_mail] = 小弟 mail list, defaultdict(list), 老大的小弟们.
  15.  
  16. way 1b, row_id(user_id) 作为节点, 做 union().
  17.  
  18. <code>
  19. from collections import defaultdict
  20. class Solution:
  21.     def accountsMerge(self, accounts):
  22.         # init
  23.         self.father = {}
  24.         father = self.father
  25.         mail_name = {}
  26.         for rec in accounts:
  27.             name = rec[0]
  28.             for mail in rec[1:]:
  29.                 mail_name[mail] = name
  30.         for mail in mail_name:
  31.             self.father[mail] = mail
  32.         for rec in accounts:
  33.             mail1 = rec[1]
  34.             for mail2 in rec[2:]:
  35.                 self.union(mail1, mail2)
  36.         group = defaultdict(list)
  37.         for mail in mail_name:
  38.             father[mail] = self.find(mail)
  39.             group[father[mail]].append(mail)
  40.         for k in group:
  41.             group[k].sort()
  42.         res = []
  43.         for k in group:
  44.             acct_name = mail_name[group[k][0]]
  45.             res.append([acct_name] + group[k])
  46.         return res
  47.    
  48.     def find(self, node):
  49.         father = self.father
  50.         if node != father[node]:
  51.             f = self.find(father[node])
  52.             father[node] = f
  53.             return f
  54.         else:
  55.             return node
  56.    
  57.     def union(self, a, b):
  58.         fa = self.find(a)
  59.         fb = self.find(b)
  60.         if fa != fb:
  61.             self.father[fa] = fb
Add Comment
Please, Sign In to add comment