美文网首页
243. Shortest Word Distance

243. Shortest Word Distance

作者: jluemmmm | 来源:发表于2021-09-30 13:26 被阅读0次

给定一个字符串数组 wordsDict,和已经存在于数组中的两个不同的字符串,返回列表中两个单词之间的最短距离。

  • 时间复杂度O(mn),空间复杂度O(1)
  • Runtime: 76 ms, faster than 82.29%
  • Memory Usage: 39.9 MB, less than 54.22%
/**
 * @param {string[]} wordsDict
 * @param {string} word1
 * @param {string} word2
 * @return {number}
 */
var shortestDistance = function(wordsDict, word1, word2) {
  let index1 = -1;
  let index2 = -1;
  let minDistance = wordsDict.length;
  for (let i = 0; i < wordsDict.length; i++) {
    if (wordsDict[i] === word1) {
      index1 = i
    } else if (wordsDict[i] === word2) {
      index2 = i
    }
    if (index1 !== -1 && index2 !== -1) {
      minDistance = Math.min(minDistance, Math.abs(index1 - index2));
    } 
  }
  return minDistance;
};

相关文章

网友评论

      本文标题:243. Shortest Word Distance

      本文链接:https://www.haomeiwen.com/subject/fjdenltx.html