1. 程式人生 > >【python3】leetcode 599. Minimum Index Sum of Two Lists(easy)

【python3】leetcode 599. Minimum Index Sum of Two Lists(easy)

599. Minimum Index Sum of Two Lists(easy)

Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.

You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.

Example 1:

Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
Output: ["Shogun"]
Explanation: The only restaurant they both like is "Shogun".

 

Example 2:

Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["KFC", "Shogun", "Burger King"]
Output: ["Shogun"]
Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).

求倆人都想去的飯店名,返回indexsum最小的飯店,如果有多個indexsum相同的最小 全部返回

1 my solution

首先求倆人都想去的飯店名,最簡單 不用遍歷的應該是set交集

然後對交集裡的每個飯店求indexsum並記錄到hashmap裡

然後得到最小的indexsum,遍歷得最小的飯店名,如果有多個最小 則全部返回

class Solution:
    def findRestaurant(self, list1, list2):
        """
        :type list1: List[str]
        :type list2: List[str]
        :rtype: List[str]
        """
        common = list(set(list1) & set(list2))
        choose = {}
        for re in common:
            indexsum = list1.index(re) + list2.index(re)
            choose[re] = indexsum
        minsum = min(choose.values())
        return [re for re,indexsum in choose.items() if indexsum == minsum]

耗時在每次都要計算index,所以不如先用2dict字典儲存每個名字的下標,直接相加 

2 dictcomps + set 交集(程式碼來自discussion)

感覺這個程式碼的dictcomps寫的太妙了 ,還有倆個dict生成的方法也。

注意:& 操作在功能上等同於intersection,但是&要求左右兩邊都要是set,而intersection只要求左邊是set

class Solution:
    def findRestaurant(self, list1, list2):
        d1,d2=({r:i for (i,r) in enumerate(l)} for l in (list1,list2))
        c=set(list1).intersection(list2)
        m=min(d1[x]+d2[x] for x in c)
        return [x for x in c if m==d1[x]+d2[x]]

3 改進我的程式碼

class Solution:
    def findRestaurant(self, list1, list2):
        """
        :type list1: List[str]
        :type list2: List[str]
        :rtype: List[str]
        """
        common = list(set(list1) & set(list2))
        d1,d2=({r:i for (i,r) in enumerate(l)} for l in (list1,list2))
        choose = {x:d1[x] + d2[x] for x in common}
        minsum = min(choose.values())
        return [re for re,indexsum in choose.items() if indexsum == minsum]