Advertisement
kosievdmerwe

Untitled

Nov 28th, 2021
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. class UnionFind:
  2.     def __init__(self, idx: int):
  3.         self.idx = idx
  4.         self.parent = self
  5.         self.height = 1
  6.    
  7.     def find(self) -> "UnionFind":
  8.         if self.parent is self:
  9.             return self
  10.        
  11.         self.parent = self.parent.find()
  12.         return self.parent
  13.    
  14.     def union(self, other: "UnionFind") -> None:
  15.         sp = self.find()
  16.         lp = other.find()
  17.         if sp is lp:
  18.             return
  19.        
  20.         if sp.height > lp.height:
  21.             sp, lp = lp, sp
  22.        
  23.         sp.parent = lp
  24.         if sp.height == lp.height:
  25.             lp.height += 1
  26.  
  27. class Solution:
  28.     def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
  29.         N = len(accounts)
  30.         ufs = [UnionFind(i) for i in range(N)]
  31.        
  32.         email_ufs = {}
  33.        
  34.         for i, account in enumerate(accounts):
  35.             uf = ufs[i]
  36.             for email in itertools.islice(account, 1, None):
  37.                 if email in email_ufs:
  38.                     email_ufs[email].union(uf)
  39.                 else:
  40.                     email_ufs[email] = uf
  41.        
  42.         ans = {}
  43.         for uf in ufs:
  44.             i = uf.idx
  45.             pi = uf.find().idx
  46.             if pi not in ans:
  47.                 ans[pi] = set()
  48.             ans[pi].update(itertools.islice(accounts[i], 1, None))
  49.        
  50.         return [
  51.             [accounts[pi][0]] + sorted(emails) for pi, emails in ans.items()
  52.         ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement