【LeetCode】599、两个列表的最小索引总和

599、Minimum Index Sum of Two Lists 两个列表的最小索引总和

难度:简单

题目描述

  • 英文:

    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.

  • 中文:

    假设Andy和Doris想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。

    你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。 如果答案不止一个,则输出所有答案并且不考虑顺序。 你可以假设总是存在一个答案。

示例

Example 1:

1
2
3
4
5
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:

1
2
3
4
5
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).

提示

  1. The length of both lists will be in the range of [1, 1000].
  2. The length of strings in both lists will be in the range of [1, 30].
  3. The index is starting from 0 to the list length minus 1.
  4. No duplicates in both lists.

代码提交

Python2,用时128ms,内存11.1M

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
dict1 = {}
for index, name in enumerate(list1):
dict1[name] = index

templist = []
tempsum = 3000
for index, name in enumerate(list2):
if name in dict1:
cursum = index+dict1[name]
if cursum < tempsum:
templist = [name]
tempsum = cursum
elif cursum == tempsum:
templist.append(name)
return templist

Tips

Python查找dict的key时,应使用if key in dict,而不是if key in dict.keys()

前者是在dict中查找,dict对象的存储结构是hash表,最优情况下查询复杂度为O(1);

后者等于是在list中查找,list对象的存储结构是线性表,查询复杂度为O(n)。

-------------本文结束感谢您的阅读-------------
0%