给定一个单词列表和两个单词 word1 和 word2,
返回列表中这两个单词之间的最短距离。
示例:
假设 words = ["practice", "makes", "perfect", "coding", "makes"]
输入: word1 = “coding”, word2 = “practice”
输出: 3
输入: word1 = “makes”, word2 = “coding”
输出: 1
你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。
/**
* @param {string[]} words
* @param {string} word1
* @param {string} word2
* @return {number}
*/
var shortestDistance = function(words, word1, word2) {
let i = 0, index1 = index2 = -1, min = Number.MAX_SAFE_INTEGER;
while(i < words.length) {
if(words[i] === word1) {
index1 = i;
} else if(words[i] === word2) {
index2 = i;
}
i++;
if(index1 > -1 && index2 > -1) {
min = Math.min(min, Math.abs(index1 - index2));
if(min === 1) {
return min;
}
}
}
return min;
};
执行用时 : 68 ms, 在所有 JavaScript 提交中击败了96.30%的用户
内存消耗 : 36.7 MB, 在所有 JavaScript 提交中击败了100.00%的用户
/**
* @param {string[]} words
* @param {string} word1
* @param {string} word2
* @return {number}
*/
var shortestDistance = function(words, word1, word2) {
let i = 0, index1 = [], index2 = [], min = Number.MAX_SAFE_INTEGER;
while(i < words.length) {
if(words[i] === word1) {
index1.push(i);
} else if(words[i] === word2) {
index2.push(i);
}
i++;
}
i = 0;
while(i < index1.length) {
let j = 0;
while(j < index2.length) {
min = Math.min(min, Math.abs(index1[i] - index2[j++]));
}
i++;
}
return min;
};
执行用时 : 72 ms, 在所有 JavaScript 提交中击败了88.89%的用户
内存消耗 : 36.7 MB, 在所有 JavaScript 提交中击败了100.00%的用户