原题目:https://leetcode-cn.com/problems/find-closest-lcci/
思路:
采用双指针,每次记录最小的距离。
代码:
class Solution {
public:
int findClosest(vector<string>& words, string word1, string word2) {
int left=-55555,right=-55555;
int ans=55555;
for(int i=0;i<words.size();i++){
if(words[i]==word1){
left=i;ans = min(ans,abs(left-right));
}
if(words[i]==word2){
right=i;ans = min(ans,abs(left-right));
}
}
return ans;
}
};