您的位置:首页 > 其它

LC-Minimum Index Sum of Two Lists

2018-03-01 16:56 344 查看
方法1:

class Solution(object):
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
common = list(set(list1)&set(list2))
res_index = []
res = []
for rest in common:
res_index.append(list1.index(rest) + list2.index(rest))
min_sum = min(res_index)
for i in range(len(res_index)):
if res_index[i] == min_sum:
res.append(common[i])
return res


方法2:

def findRestaurant(self, A, B):
Aindex = {u: i for i, u in enumerate(A)}
best, ans = 1e9, []

for j, v in enumerate(B):
i = Aindex.get(v, 1e9)
if i + j < best:
best = i + j
ans = [v]
elif i + j == best:
ans.append(v)
return ans


0,自己写的代码

1,题目要求:

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.



用通俗的话来说,就是找到两个人都爱吃的餐厅,同时都是相对比较爱吃的。两个list可以看成是对于餐厅的喜爱程度进行排序后的一个结果,越往前,越爱吃。

就像Example2中,最燃两个人都爱吃Burger King,但是相对于Shogun来说,二者都更爱吃一些,也就是index的和更小。

2,题目本身不难,先做一个交集取出二者都爱吃的餐厅;然后再依次找到index和的大小;最后再做判断。

在方法2中,是別人写的一种算法。

主要用到的是enumerate方法,也就是得到每个字符串的index以及index,

s1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"]
for j, v in enumerate(s1):
print j, v

output:
0 Shogun
1 Tapioca Express
2 Burger King
3 KFC
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: