1. 程式人生 > >【LeetCode】721. Accounts Merge 解題報告(Python)

【LeetCode】721. Accounts Merge 解題報告(Python)

題目描述:

Given a list accounts, 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 email that is common 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", "[email protected]", "[email protected]
"], ["John", "[email protected]"], ["John", "[email protected]", "[email protected]"], ["Mary", "[email protected]"]] Output: [["John", '[email protected]', '[email protected]', '[email protected]'], ["John", "[email protected]"], ["Mary", "[email protected]"]] Explanation: The first and third John's are the same person as they have the common email "
[email protected]
". The second John and Mary are different people as none of their email addresses are used by other accounts. We could return these lists in any order, for example the answer [['Mary', 'mary[email protected]'], ['John', '[email protected]'], ['John', '[email protected]', '[email protected]', '[email protected]']] would still be accepted.

Note:

  1. The length of accounts will be in the range [1, 1000].
  2. The length of accounts[i] will be in the range [1, 10].
  3. The length of accounts[i][j] will be in the range [1, 30].

題目大意

給出一個賬戶列表,其中每一個賬戶由多個字串組成,第一個字串為姓名,其餘的字串為在該姓名下注冊的郵箱地址。由於同一個人可能有兩個不同的賬戶,判別是否是同一個人所擁有的賬戶方法就是在不同的賬戶中發現是否有相同的郵箱地址,如果有相同的郵箱地址,則可判定兩個賬戶為同一人所擁有。現在要做的就是,對給定賬戶列表中同一個人所擁有的賬戶進行合併,合併結果為一個人只擁有一個賬戶,並且該賬戶包含其所有的郵箱並且不重複。 Note:同一人的賬戶可能有多個重名郵箱地址,輸出的時候要對這部分進行處理去掉冗餘部分,並且進行字典序排列。

解題方法

這個題的解法是並查集,LeetCode 721. Accounts Merge對這個題有非常詳細的講解,包括並查集的知識,我就不班門弄斧了。另外,我把這個c++程式碼用python實現了一遍,時間複雜度應該比c++還要低一點,可是通過不了啊……尷尬。

這個問題本質上是對不同的集合進行處理,因此暴力求解法在這裡幾乎不可能成功。求解這個問題的方法最經典的思路就是並查集。

那麼在本題所涉及的條件下,我們應該滿足兩個要求。

去除重複元素,並且有序排序

對於這個條件,很容易想到set集合(結合中沒有重複元素,而且元素在插入的時候保持字典序),因此在實現的過程中,必要的一步就是將原有的郵箱列表裝載到一個set集合中,然後進行如下的操作。

對含有相同元素的集合,進行合併。

這個步驟中,就要我們的剛學的並查集登場了。

  1. 首先初始化並查集,使並查集和中的元素(i = 0,1,2…n)與account中的元素(account[0], account1…account[n])一一對應。
  2. 在對應結束後,我們便可以將所有的集合元素遍歷一遍,判斷哪些集合會有相同的元素。凡是有相同郵箱的賬戶均合併(此操作在並查集中實現)。
  3. 進行完上面的步驟之後,哪些account是屬於同一人的,這些關係均會在並查集上體現出來。最後,我們按照並查集的操作,來將元素進行合併即可。

程式碼如下,並沒有通過OJ.

class Solution(object):
    def accountsMerge(self, accounts):
        """
        :type accounts: List[List[str]]
        :rtype: List[List[str]]
        """
        n = len(accounts)
        self.par = [x for x in range(n)]
        nameMap = collections.defaultdict(list)
        for i, account in enumerate(accounts):
            nameMap[account[0]].append(i)
        for i in range(n):
            for j in nameMap[accounts[i][0]]:
                if (not self.same(i, j)) and (set(accounts[i][1:]) & set(accounts[j][1:])):
                    self.union(i, j)
        res = [set() for _ in range(n)]
        for i in range(n):
            self.par[i] = self.find(i)
            res[self.par[i]] |= set(accounts[i][1:])
        ans = []
        for i in range(n):
            if self.par[i] == i:
                person = list()
                person.append(accounts[i][0])
                person.extend(sorted(res[i]))
                ans.append(person)
        return ans
        
        
    def find(self, x):
        if x == self.par[x]:
            return self.par[x]
        parent = self.find(self.par[x])
        self.par[x] = parent
        return parent
    
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        self.par[x] = y
    
    def same(self, x, y):
        return self.find(x) == self.find(y)

參考資料:

日期

2018 年 9 月 30 日 —— 9月最後一天啦!