LeetCode 题解工作台
两个列表的最小索引总和
给定两个字符串数组 list1 和 list2 ,找到 索引和最小的公共字符串 。 公共字符串 是同时出现在 list1 和 list2 中的字符串。 具有 最小索引和的公共字符串 是指,如果它在 list1[i] 和 list2[j] 中出现,那么 i + j 应该是所有其他 公共字符串 中的最小…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们用一个哈希表 记录 中的字符串和它们的下标,用一个变量 记录最小的下标和。 然后遍历 ,对于每个字符串 ,如果 在 中出现,那么我们计算 在 中的下标 和在 中的下标 ,如果 $\textit{i} + \textit{j} < \textit{mi}$,我们就更新答案数组 为 ,并且更新 为 $\textit{i} + \textit{j}$;如果 $\textit{i…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给定两个字符串数组 list1 和 list2,找到 索引和最小的公共字符串。
公共字符串 是同时出现在 list1 和 list2 中的字符串。
具有 最小索引和的公共字符串 是指,如果它在 list1[i] 和 list2[j] 中出现,那么 i + j 应该是所有其他 公共字符串 中的最小值。
返回所有 具有最小索引和的公共字符串。以 任何顺序 返回答案。
示例 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”,它有最小的索引和 = (0 + 1) = 1。
示例 3:
输入:list1 = ["happy","sad","good"], list2 = ["sad","happy","good"] 输出:["sad","happy"] 解释:有三个公共字符串: "happy" 索引和 = (0 + 1) = 1. "sad" 索引和 = (1 + 0) = 1. "good" 索引和 = (2 + 2) = 4. 最小索引和的字符串是 "sad" 和 "happy"。
提示:
1 <= list1.length, list2.length <= 10001 <= list1[i].length, list2[i].length <= 30list1[i]和list2[i]由空格' '和英文字母组成。list1的所有字符串都是 唯一 的。list2中的所有字符串都是 唯一 的。
解题思路
方法一:哈希表
我们用一个哈希表 记录 中的字符串和它们的下标,用一个变量 记录最小的下标和。
然后遍历 ,对于每个字符串 ,如果 在 中出现,那么我们计算 在 中的下标 和在 中的下标 ,如果 ,我们就更新答案数组 为 ,并且更新 为 ;如果 ,我们就将 加入答案数组 。
遍历结束后,返回答案数组 即可。
class Solution:
def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
d = {s: i for i, s in enumerate(list2)}
ans = []
mi = inf
for i, s in enumerate(list1):
if s in d:
j = d[s]
if i + j < mi:
mi = i + j
ans = [s]
elif i + j == mi:
ans.append(s)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Understanding hash table usage for index lookup.
- question_mark
Ability to handle edge cases where multiple strings have the same index sum.
- question_mark
Proficiency in optimizing solutions with linear complexity.
常见陷阱
外企场景- error
Not considering the possibility of multiple strings having the same index sum.
- error
Failure to handle large lists efficiently within time constraints.
- error
Incorrectly updating the result list when a new minimum index sum is found.
进阶变体
外企场景- arrow_right_alt
Find the common strings with the smallest index sum in sorted order.
- arrow_right_alt
Extend the problem to handle case insensitivity when comparing strings.
- arrow_right_alt
Modify the problem to return the total minimum index sum, not just the strings.