This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it?
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.
For example,Assume that words = ["practice", "makes", "perfect", "coding", "makes"]
.
Given word1 = “coding”, word2 = “practice”, return 3.
Given word1 = "makes", word2 = "coding", return 1.
Note:You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
Solution:
這題和243的區別是,求兩個word的最短距離的函數會被多次調用。如果是用243的方法,每求一次兩個詞的最短距離,則每次都需要遍歷整個數組,求k對word的復雜度為O(kn).
如果利用HashMap<String, ArrayList<Integer>> 來存儲每個單詞出現的每一個index,求特定兩個單詞的最小距離時只需要關注兩個詞所對應的兩個index的list就可以了。
已知兩個詞各自的index的list,求最小距離的思路:
1. 分別用i,j兩個指針指向兩個index list的開頭。
2. 求i,j當前指向的index的差,并判斷是否更新minDistance;
如果 i 所對應的 index 小于 j 所對應的 index,則 i++,否則 j++;(增大較小的index,讓 i 和 j 所對應的index盡量靠近,從而求出最小的distance);
3. 重復步驟2直到 i 或者 j 不再小于各自index list的長度(直到越界)
code:
public class WordDistance {
public HashMap<String, ArrayList<Integer>> hm;
public WordDistance(String[] words)
{
hm = new HashMap<>();
for(int i = 0; i < words.length; i ++)
{
if(!hm.containsKey(words[i]))
hm.put(words[i], new ArrayList<>());
hm.get(words[i]).add(i);
}
}
public int shortest(String word1, String word2)
{
ArrayList<Integer> list1 = hm.get(word1);
ArrayList<Integer> list2 = hm.get(word2);
int i = 0, j = 0;
int minDistance = Integer.MAX_VALUE;
while(i < list1.size() && j < list2.size())
{
int index1 = list1.get(i);
int index2 = list2.get(j);
int curDistance = Math.abs(index1 - index2);
if(curDistance < minDistance)
minDistance = curDistance;
if(index1 < index2) i ++;
else j ++;
}
return minDistance;
}
}
// Your WordDistance object will be instantiated and called as such:
// WordDistance wordDistance = new WordDistance(words);
// wordDistance.shortest("word1", "word2");
// wordDistance.shortest("anotherWord1", "anotherWord2");