• 题目要求:

image.png

  • 思路:

    • 定义一个dist来表示word1和word2出现的时候的数组下标的差值
    • 遍历数组,如果出现了新的值等于word1或word2的值,如果出现的是word1,把当前的下标减去之前出现的word2的下标,绝对值如果小于dist,把新的dist赋给dist,直至循环结束。
  • 核心代码
# 把dist定义为数组长度,或者是无穷也可以,因为题中说word1和word2都一定在words中,所以他们出现的最远距离就是len(words)
dist = len(words)
# 定义三个值,index为当前遍历到的位置,index1记录word1出现的位置,index2记录word2出现的位置。
index , index1 , index2 = 0 , None , None
# 遍历words
while index < len(words):
    # 如果出现了word1,把下标记录下来
    if words[index] == word1:
        index1 = index
    # 如果出现了words2,把下标记录下来
    if words[index] == word2:
        index2 = index
    # 如果index1 与 index2 都不为None,也就是word1和word2都出现过了,计算一下他们的距离,并与之前的距离做比较,把距离更小的那个保存下来
    if index1 is not None and index2 is not None:
        dist = min(dist,abs(index2-index1))
    index += 1
return dist
  • 完整代码:
class Solution(object):
    def shortestDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        dist = len(words)
        index , index1 , index2 = 0 , None , None
        while index < len(words):
            if words[index] == word1:
                index1 = index
            if words[index] == word2:
                index2 = index
            if index1 is not None and index2 is not None:
                dist = min(dist,abs(index2-index1))
            index += 1
        return dist


Adrianna
1 声望2 粉丝