单词距离
难度:
标签:
题目描述
You have a large text file containing words. Given any two different words, find the shortest distance (in terms of number of words) between them in the file. If the operation will be repeated many times for the same file (but different pairs of words), can you optimize your solution?
Example:
Input: words = ["I","am","a","student","from","a","university","in","a","city"], word1 = "a", word2 = "student" Output: 1
Note:
words.length <= 100000
代码结果
运行时间: 54 ms, 内存: 32.6 MB
/*
* 思路:
* 1. 使用流遍历单词数组,记录两个单词出现的位置。
* 2. 使用一个列表来存储两个单词的位置。
* 3. 使用流计算所有位置对的距离,并找出最小距离。
*/
import java.util.*;
import java.util.stream.*;
public class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
List<Integer> positions1 = IntStream.range(0, words.length)
.filter(i -> words[i].equals(word1))
.boxed()
.collect(Collectors.toList());
List<Integer> positions2 = IntStream.range(0, words.length)
.filter(i -> words[i].equals(word2))
.boxed()
.collect(Collectors.toList());
return positions1.stream()
.flatMapToInt(p1 -> positions2.stream().mapToInt(p2 -> Math.abs(p1 - p2)))
.min()
.orElse(Integer.MAX_VALUE);
}
}
解释
方法:
题解使用了双指针技术来找出两个指定单词的最短距离。首先,初始化两个指针 pre1 和 pre2 为一个非常大的数(题中使用了100000),这两个指针将分别记录最近一次遇到 word1 和 word2 的索引位置。然后遍历整个单词列表,每当找到一个 word1 或 word2,就更新相应的指针,并计算与另一个单词上次出现位置的距离,取所有这些距离的最小值作为结果。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么在初始化 pre1 和 pre2 时选择了 100000 这个值?这个值是否与输入的 words 数组长度有关?
▷🦆
如果在遍历过程中,遇到的第一个单词是 word2 而不是 word1,此时计算的距离是否准确?
▷🦆
在解决方案中,提到了如何优化多次查询的情况,具体是如何实现的?
▷