[Leetcode] 721. Accounts Merge

jong_p·2021년 11월 29일
0

영혼의 알고리즘

목록 보기
12/19

21-11-29
sovled in poor way

Problem

Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.

Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.

After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.

Example 1:

Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]


Solution

class Solution:
    def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
        dic={}
        ans=[]
        for account in accounts:
            target=None
            for i in range(1,len(account)):
                if hash(account[i]) in dic:
                    target=dic[hash(account[i])]
            
            if not target:
                ans.append(account)
                for i in range(1,len(account)):
                    dic[hash(account[i])]=account
            else:
                for i in range(1,len(account)):
                    if hash(account[i]) not in dic:
                        dic[hash(account[i])]=target
                        target.append(account[i])
                        
        print(ans)         
        #sorting
        for i,v in enumerate(ans):
            tmp=v[:1]+sorted(list(set(v[1:])))
            ans[i]=tmp
                        
        return ans

hashtable을 이용해서 쌩어거지로 풀었다. wrong answer 못 봤으면 못 풀었을 것 같다.

그래프가 안 보여도 DFS/BFS가 생각날 수 있다.


Best Solution

def accountsMerge(self, accounts):
    neighbor_dic = collections.defaultdict(set)
    name_dic = {}
    for lst in accounts:
        name = lst[0]
        for email in lst[1:]:
            neighbor_dic[email].add(lst[1])
            neighbor_dic[lst[1]].add(email)
            name_dic[email] = name
                   
    res = []
    seen = set()
    for key in neighbor_dic.keys():
        if key not in seen:
            seen.add(key)
            stack = [key]
            tmp = [key]
            while stack:
                u = stack.pop()
                for n in neighbor_dic[u]:
                    if n not in seen:
                        seen.add(n)
                        tmp.append(n)
                        stack.append(n)
            res.append([name_dic[key]]+sorted(tmp))
    return res

이메일을 node로 보면 그래프처럼 탐색할 수 있다. 혹은 하나의 그래프를 기준으로, 같은 이메일을 가진 다른 account를 확장해서 더해나간다고 생각해도 DFS, BFS로 생각할 수 있다.

profile
알고리즘 정리 좀 해볼라고

0개의 댓글