-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path245.shortest-word-distance-iii.js
52 lines (46 loc) · 1.2 KB
/
245.shortest-word-distance-iii.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
* @lc app=leetcode id=245 lang=javascript
*
* [245] Shortest Word Distance III
*/
/**
* @param {string[]} words
* @param {string} word1
* @param {string} word2
* @return {number}
*/
var sameWordDistance = function(words, word1) {
var lastIndex;
var distance = Infinity;
// Search every word
for (var i = 0; i < words.length; i++) {
// word1 found
if (words[i] === word1) {
// If lastIndex exists, compare minimum distances
if (lastIndex !== undefined) {
distance = Math.min(distance, Math.abs(lastIndex - i));
}
// Update lastIndex
lastIndex = i;
}
}
return distance;
};
var shortestWordDistance = function(words, word1, word2) {
//one pass, one index, time: O(N), space:O(1)
if (word1 === word2) {
return sameWordDistance(words, word1);
}
var potentialWordIndex = -1,
ans = Number.MAX_SAFE_INTEGER;
for (var i = 0; i < words.length; i++) {
if (words[i] === word1 || words[i] === word2) {
if (potentialWordIndex !== -1 && words[potentialWordIndex] !== words[i]) {
//finding the another word0
ans = Math.min(i - potentialWordIndex, ans);
}
potentialWordIndex = i;
}
}
return ans;
};