解题思路:
一道非常简单的数组题,定义两个index分别指向当前最近访问到的word1和word2的下标,然后更新二者最小差值即可,代码如下:
class Solution {
public:
int findClosest(vector<string>& words, string word1, string word2) {
int dis = INT_MAX;
int index1 = -1, index2 = -1;
for(int i = 0; i < words.size(); i ++) {
if(words[i] == word1) {
index1 = i;
if(index2 != -1) {
dis = min(dis, index1 - index2);
}
}
if(words[i] == word2) {
index2 = i;
if(index1 != -1) {
dis = min(dis, index2 - index1);
}
}
}
return dis;
}
};