# Code language: Python classSolution: deffindClosest(self, words: List[str], word1: str, word2: str) -> int: ans = 0x7fffffff # a, b 记录两个单词出现的位置 a, b = -ans, ans for i, j inenumerate(words): if j == word1: a = i elif j == word2: b = i ans = min(ans, abs(a - b)) return ans
1 2 3 4 5 6 7 8 9 10 11 12 13
// Code language: Cpp classSolution { public: intfindClosest(vector<string>& words, string word1, string word2){ int ans = 0x7fffffff, a = 0x3f3f3f3f, b = 0xf0000000; for (int i = 0, n = words.size(); i < n; ++i) { if (words[i] == word1) a = i; elseif (words[i] == word2) b = i; ans = min(ans, a > b ? a - b : b - a); } return ans; } };
1 2 3 4 5 6 7 8 9 10 11 12
// Code language: Java classSolution { publicintfindClosest(String[] words, String word1, String word2) { intans=0x7fffffff, a = 0x3f3f3f3f, b = 0xf0000000; for (inti=0, n = words.length; i < n; ++i) { if (words[i].equals(word1)) a = i; elseif (words[i].equals(word2)) b = i; ans = Math.min(ans, a > b ? a - b : b - a); } return ans; } }
时间复杂度: \(O(n)\)
空间复杂度: \(O(1)\)
哈希表
若按照题目要求多次调用,那么可以使用哈希表记录所有单词的出现位置,然后再使用双指针求解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Code language: Python classSolution: deffindClosest(self, words: List[str], word1: str, word2: str) -> int: w = defaultdict(list) for i, j inenumerate(words): w[j].append(i) w1, w2 = w[word1], w[word2] ans = abs(w1[0] - w2[0]) n1, n2 = len(w1), len(w2) i, j = 0, 0 while i < n1 and j < n2: if j == n2 - 1or (w1[i] < w2[j]): i += 1 else: j += 1 if i < n1 and j < n2: ans = min(ans, abs(w1[i] - w2[j])) return ans