原题链接:面试题 17.11. 单词距离
solution:
哈希表+双指针。哈希表存储每个单词的所有位置。双指针遍历查找最近距离
class Solution {
public:
int findClosest(vector<string>& words, string word1, string word2) {
int dist = INT_MAX;
unordered_map<string, vector<int>> map;
for(int i = 0;i < words.size();i++) {
map[words[i]].push_back(i);
}
vector<int> res1 = map[word1];
vector<int> res2 = map[word2];
/*暴力做法
for(int i = 0;i < res1.size();i++)
for(int j = 0;j < res2.size();j++) {
dist = min(dist, abs(res1[i] - res2[j]));
}
*/
/*双指针*/
for(int i = 0,j = 0;i < res1.size() && j < res2.size();) {
dist = min(dist, abs(res1[i] - res2[j]));
if(res1[i] < res2[j]) i++;
else j++;
}
return dist;
}
};