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]