【LeetCode】面试题 17.11. 单词距离

135 阅读2分钟

image.png

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第10天,点击查看活动详情

测试岗位也越来卷了,除了基本的功能测试外,还要有编程基础、脚本经验才脱颖而出。

怎么才能提高我们的编程能力呢,刷LeetCode是最佳的途径之一,话不多数,刷题走起~

一、题目描述:

  • 题目内容

    image.png

  • 题目示例

    image.png

  • 题目解析

    • 题目中给出三个参数:words,word1,word2
    • words.length <= 100000

二、思路分析:

我们拿到本题,读取题意要求求出 word1 和 word2在列表 words 中最短距离。

根据题目示列,我们可以明确两点信息:

  1. words 列表中可以出现重复元素
  2. words 列表中必定存在 word1 和 word2

解答该题,我们很容易想到使用 贪心算法 来解决,思路如下:

  • 定义两个指针w1,w2.分别记录找到word1和word2的索引位置,初始赋值为-10000,10000

  • 计算abs(w1-w2)的距离,直到遍历完成取最小距离结果

  • for循环遍历words列表,寻找word1和word2的位置 image.png

  • 当words[i]与word1相等时,则w1记录word1的位置

  • 当words[i]与word2相等时,则w2记录word2的位置 image.png

  • 直到遍历完words列表,返回最小值

image.png

我们可以轻松的使用python实现代码如下:

class Solution(object):
    def findClosest(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """

        w1 = -10000
        w2 = 10000
        res = 10000

        for i,word in enumerate(words):

            if word == word1:
                w1 = i
            if word == word2:
                w2 = i

            res = min(res,abs(w1-w2))

        return res

但是,我们发现上述代码,对于words列表的元素都要进行abs(w1-w2)的计算

  • 可以添加continue关键字,当遍历到不是word1和word2的元素时,则直接跳过abs(w1-w2)计算
class Solution(object):
    def findClosest(self, words, word1, word2):
        w1 = -10000
        w2 = 10000
        res = 10000
        for i,word in enumerate(words):
            if word == word1:
                w1 = i
            elif word == word2:
                w2 = i
            else:
                continue
            res = min(res,abs(w1-w2))
        return res

三、总结:

本题考察双指针遍历列表,如下是使用continue关键字优化,AC记录如下:

image.png

  • 时间复杂度O(N), words列表长度
  • 空间复杂度O(1)

以上是本期内容,欢迎大佬们点赞评论,下期见~~~