题目
有个内含单词的超大文本文件,给定任意两个不同的单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,你能对此优化吗?
- words.length <= 100000
题解
双指针记录两个单词出现的位置,取最小值,但需要注意的是两指针的初始值的绝对值为题设String数组长度的最大值,以避免某个单词出现后,在比较时导致最短距离被无意缩小
class Solution {
public int findClosest(String[] words, String word1, String word2) {
int idx1 = -100000, idx2 = 100000;
int res = Integer.MAX_VALUE;
for(int i = 0; i < words.length; ++i) {
String word = words[i];
if(word1.equals(word)) idx1 = i;
if(word2.equals(word)) idx2 = i;
res = Math.min(res, Math.abs(idx1 - idx2));
}
return res;
}
}