Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters.
Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"]
.
Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1
题意:
还是数组中两个单词的最短距离。
相对于之前[leetcode]243. Shortest Word Distance最短单词距离
这题要求对于function,允许连环call(言外之意是,不能naive的扫数组了)
Solution1: HashMap + Merge Sort
1. Since "method will be called repeatedly many times", it will cost much time to scan the whole input String array again and again.
We can use a hashmap in advance, saving each string as a key and its corresponding indices as a value.
2. Use pointer i, j to scan list1, list2 seperately, updating the shortest distance.
code
class WordDistance {
HashMap <String, List<Integer>> map; public WordDistance(String[] words) {
map = new HashMap<>();
for(int i = 0 ; i< words.length; i++){
String w = words[i];
if(map.containsKey(w)){
map.get(w).add(i);
}else{
List<Integer> list = new ArrayList<>();
list.add(i);
map.put(w, list);
}
} } public int shortest(String word1, String word2) {
List<Integer> l1 = map.get(word1);
List<Integer> l2 = map.get(word2);
// --------------merger sort 思想 | ------------------------
// --------------merger sort \|/ ------------------------
int result = Integer.MAX_VALUE;
int i = 0;
int j = 0;
while(i<l1.size() && j<l2.size()) {
result = Math.min(result, Math.abs(l1.get(i)- l2.get(j)));
if(l1.get(i)<l2.get(j)){
i++;
}else{
j++;
}
}
// --------------merger sort------------------------
return result;
}
}
复杂度:
时间
存储:O(N) map是用来存储的。用时为扫一遍given array的时间。
查找:O(m+n) list是用来查找的。用时为扫list1的时间+扫list2的时间。
空间
存储:O(N) map是用来存储的。将whole array的元素都放入了map。 (内心OS:map的空间是由key的个数决定的)
查找:O(N) list是用来查找的。 list所占空间为each string的corresponding