题目描述
思路
遍历
最直观的做法为遍历数组words,对于数组中的每个word1,遍历数组words找到每个word2并计算距离,时间复杂度为O(n^2)。这个解法有优化空间。可以从左往右遍历words,当遍历到word1时,如果已遍历的单词中存在word2,为计算最短距离,可以取最后一个已经遍历到的word2所在的下标来计算距离。同理,遍历到word2时,则取最后一个word1的下标计算距离。
上述最后一个已经遍历到的word1和word2可以分别用index1和index2表示,则节省了使用数组存储下标位置的空间。初始化两个下标都为-1,如果遍历到word1则更新index1,如果遍历到word2,更新index2;如果index1和index2都大于0,则计算两个index的差的绝对值,用这个绝对值更新最短距离。遍历结束返回结果即可。
Python实现
class Solution:
def findClosest(self, words: List[str], word1: str, word2: str) -> int:
ans, idx1, idx2 = len(words), -1, -1
for i, word in enumerate(words):
if word == word1:
idx1 = i
elif word == word2:
idx2 = i
if idx1 >= 0 and idx2 >= 0:
ans = min(ans, abs(idx2-idx1))
return ans
Java实现
class Solution {
public int findClosest(String[] words, String word1, String word2) {
int ans = words.length, idx1 = -1, idx2 = -1;
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (word.equals(word1)) {
idx1 = i;
} else if (word.equals(word2)) {
idx2 = i;
}
if (idx1 >= 0 && idx2 >= 0) {
ans = Math.min(ans, Math.abs(idx2-idx1));
}
}
return ans;
}
}
C++实现
class Solution {
public:
int findClosest(vector<string>& words, string word1, string word2) {
int length = words.size();
int ans = length, idx1 = -1, idx2 = -1;
for (int i = 0; i < length; i++) {
string word = words[i];
if (word == word1) {
idx1 = i;
} else if (word == word2) {
idx2 = i;
}
if (idx1 >= 0 && idx2 >= 0) {
ans = min(ans, abs(idx2 - idx1));
}
}
return ans;
}
};