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.
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).
题目大意:
让我们找到坐标位置之和最小的相同的字符串
注意:
列表长度范围[1, 1000]
字符串长度[1, 30]
下标范围[0, len - 1]
列表内无重复
对于这种数组项和其坐标之间关系的题,最先考虑到的就是要建立数据和其位置坐标之间的映射。我们建立list1的值和坐标的之间的映射,然后遍历list2,如果当前遍历到的字符串在list1中也出现了,那么我们计算两个的坐标之和,如果最小坐标和当前坐标和相同,那么将这个字符串加入结果result中,如果当前坐标和比最小坐标和小,那么更新为这个较小值,然后将结果result清空并加入这个字符串
注意:因为可能存在多个最小值,返回的是list,所以需要额外判断一下相等的情况
class Solution(object):
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
hashmap = {}
result = []
indexsum = len(list1) + len(list2)
for i in xrange(len(list1)):
hashmap[list1[i]] = i
for i in xrange(len(list2)):
if list2[i] in hashmap:
if hashmap[list2[i]] + i < indexsum:
result = [list2[i]]
indexsum = hashmap[list2[i]] + i
elif hashmap[list2[i]] + i == indexsum:
result.append(list2[i])
return result
Last updated
Was this helpful?