# [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] 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
for email in lst[1:]:
name_dic[email] = name

res = []
seen = set()
for key in neighbor_dic.keys():
if key not in seen:
stack = [key]
tmp = [key]
while stack:
u = stack.pop()
for n in neighbor_dic[u]:
if n not in seen:
return res