Daily LeetCode 599. Minimum Index Sum of Two Lists
https://leetcode.com/problems/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:
1 | Input: |
Example 2:
1 | Input: |
Note:
- The length of both lists will be in the range of [1, 1000].
- The length of strings in both lists will be in the range of [1, 30].
- The index is starting from 0 to the list length minus 1.
- No duplicates in both lists.
题目分析:
这一题其实难度不大,但我一开始看错了题,我以为只要输出一个相对来说两个人都喜欢的餐馆即可。后来各种WA后,才发现,只要index
之和相等的餐厅,都需要输出。
这一题需要设置两个字典,分别保存Andy
和Doris
感兴趣的餐厅restaurant
以及对应的index
,字典格式为:{restaurant: index}
。接着,我们遍历list2
,找到相同元素时,将自身index
和对应元素在另一个字典中的index
相加,寻找最小的index
之和,并将最小index
和的餐厅添加到res
中。
代码:
1 | class Solution(object): |