721. Accounts Merge

https://leetcode.com/problems/accounts-merge/

solution

  • 并查集

# https://leetcode.com/problems/accounts-merge/solutions/1084738/python-the-clean-union-find-solution-you-are-looking-for/

class UF:
    def __init__(self, n):
        self.parents = list(range(n))

    def union(self, child, parent):
        self.parents[self.find(child)] = self.find(parent)

    def find(self, x):
        if x != self.parents[x]:
            self.parents[x] = self.find(self.parents[x])
        return self.parents[x]

class Solution:
    def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
        uf = UF(n=len(accounts))

        email_to_index = {}
        for i, account in enumerate(accounts):
            emails = account[1:]
            for email in emails:
                if email in email_to_index:
                    uf.union(i, email_to_index[email])
                email_to_index[email] = i

        ans = collections.defaultdict(list)
        for email, index in email_to_index.items():
            ans[uf.find(index)].append(email)

        return [[accounts[i][0]] + sorted(emails) for i, emails in ans.items()]

时间复杂度:O() 空间复杂度:O()

  • dfs

  • 集合

  • bfs

Last updated