题目难度: 中等
原题链接[1]
今天继续更新程序员面试金典系列, 大家在公众号 算法精选 里回复 面试金典 就能看到该系列当前连载的所有文章了, 记得关注哦~
有个内含单词的超大文本文件,给定任意两个不同的单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,你能对此优化吗?
class Solution:
def findClosest(self, words: List[str], word1: str, word2: str) -> int:
# 单次遍历+维护两最后下标
i1, i2 = -1, -1
res = float("inf")
for i, w in enumerate(words):
if w == word1:
# 更新单词1最后出现下标
i1 = i
if i2 != -1:
# 单词2前面出现过, 得到一个有效距离, 用它更新最终结果
res = min(res, i1 - i2)
elif w == word2:
# 更新单词2最后出现下标
i2 = i
if i1 != -1:
# 单词1前面出现过, 得到一个有效距离, 用它更新最终结果
res = min(res, i2 - i1)
return res
class Solution:
def findClosest(self, words: List[str], word1: str, word2: str) -> int:
# 下标字典+双指针
# 这里前提是words保持不变, 每次只变化word1和word2参数
# 所以理论上下面的预处理部分应该放在单独的init函数
# 预处理部分, 得到单词到其所有下标的映射字典
d = collections.defaultdict(list)
for i, w in enumerate(words):
d[w].append(i)
# 查找部分
arr1, arr2 = d[word1], d[word2]
i, j = 0, 0
res = float("inf")
while i < len(arr1) and j < len(arr2):
# 更新最短距离
res = min(res, abs(arr1[i] - arr2[j]))
if arr1[i] < arr2[j]:
# 单词1下标更小, 移动它
i += 1
else:
# 单词2下标更小, 移动它
j += 1
return res
[1]
原题链接: https://leetcode.cn/problems/find-closest-lcci/
留言与评论(共有 0 条评论) “” |