leetcode 721账户合并-并查集+小根堆

 (1)以字典方式构建构建并查集,用于联通同一user的email

class UnionSet:
    def __init__(self):
        self.father = dict()
    def find(self, name):
        if name not in self.father:
            self.father[name] = name
            return name
        if self.father[name] == name:
            return name
        self.father[name] = self.find(self.father[name])
        return self.father[name]
    def union(self, x, y): #将y并入x类
        root_x = self.find(x) #x位置元素,根节点为root_x编号元素
        root_y = self.find(y) #y位置元素,根节点为root_y编号元素
        if root_x != root_y:              
            self.father[root_y] = root_x #把root_y编号元素的父节点,替换为root_x
        return

(2)由于name不唯一,email唯一。构建 email2name的映射同时通过并查集联结email

(3)遍历所有email,得到并查集中email根节点对应的emails

(4)通过email2name,得到email根节点 对应的name,并弹出emails

class Solution:
    def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
        us = UnionSet()
        email2name = dict()
        for account in accounts:
            name = account[0]
            index = len(account)
            for i in range(1, index):
                email2name[account[i]] = name
                if i != index - 1:
                    us.union(account[i], account[i + 1])

        email2emails = collections.defaultdict(list) ##构建email根节点的最小堆
        for i in email2name:
            heapq.heappush(email2emails[us.find(i)], i) 

        result = []
        for email, emails in email2emails.items():
            tmp = []
            name = email2name[email]
            tmp.append(name)
      
            for i in range(len(emails)):
                tmp.append(heapq.heappop(emails))
            result.append(tmp)
        return result

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值