持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第13天,点击查看活动详情
1.描述
599. 两个列表的最小索引总和 - 力扣(LeetCode)
假设 Andy 和 Doris 想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。
你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。 如果答案不止一个,则输出所有答案并且不考虑顺序。 你可以假设答案总是存在。
示例 1:
输入: list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"],list2 = ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
输出: ["Shogun"]
解释: 他们唯一共同喜爱的餐厅是“Shogun”。
示例 2:
输入:list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"],list2 = ["KFC", "Shogun", "Burger King"]
输出: ["Shogun"]
解释: 他们共同喜爱且具有最小索引和的餐厅是“Shogun”,它有最小的索引和1(0+1)。
提示:
- 1 <= list1.length, list2.length <= 1000
- 1 <= list1[i].length, list2[i].length <= 30
- list1[i] 和 list2[i] 由空格 ' ' 和英文字母组成。
- list1 的所有字符串都是 唯一 的。
- list2 中的所有字符串都是 唯一 的。
2.分析
看到题目索引和共同喜爱的餐厅时立刻想到python built-in funtion: index(),直接返回字符串在列表中的索引。 那么解题思路就是:先设置一个least 代表最小索引,然后遍历任意一个列表,对于列表中的每一个字符串检查:
- 当前索引是否超过了least,如果超过直接跳出循坏返回ans
- 如果该字符串同时在两个list里:
- 如果索引和大于list:不管,遍历到下一个字符串
- 如果索引和小于list:代表之前的餐厅不是最小索引和的餐厅,清空ans,把该字符串装进去
- 如果索引和等于list:直接把字符串装进 ans
3.AC代码
class Solution:
def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
ans = []
least = len(list1)+len(list2)
# set least index to a large number
for res in list1:
if list1.index(res) > least:
break
# larger than least, break and return
elif res in list2:
if list1.index(res) + list2.index(res) > least:
continue
# larger than least, go for next res
elif list1.index(res) + list2.index(res) < least:
ans.clear()
least = list1.index(res) + list2.index(res)
#
ans.append(res)
# append if sum of both indexs <= least
return ans