题目
解题方法
设置三个变量word1的当前索引 word1ind = -len(words)、word2的当前索引 word2ind = len(words)、最小距离distance = len(words),遍历数组,当遇到word1或word2时更新其当前索引,并更新distance = min(distance, abs(word1ind - word2ind)),否则如果不是word1或word2,pass。最后返回distance。
时间复杂度:O(n)
空间复杂度:O(1)
代码
class Solution:
def shortestDistance(self, words: List[str], word1: str, word2: str) -> int:
word1ind = -len(words)
word2ind = len(words)
distance = len(words)
for i in range(len(words)):
if words[i] == word1:
word1ind = i
distance = min(distance, abs(word1ind - word2ind))
elif words[i] == word2:
word2ind = i
distance = min(distance, abs(word1ind - word2ind))
else:
pass
return distance