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的區(qū)別是,求兩個(gè)word的最短距離的函數(shù)會(huì)被多次調(diào)用广鳍。如果是用243的方法屁桑,每求一次兩個(gè)詞的最短距離愚争,則每次都需要遍歷整個(gè)數(shù)組,求k對(duì)word的復(fù)雜度為O(kn).
如果利用HashMap<String, ArrayList<Integer>> 來存儲(chǔ)每個(gè)單詞出現(xiàn)的每一個(gè)index推盛,求特定兩個(gè)單詞的最小距離時(shí)只需要關(guān)注兩個(gè)詞所對(duì)應(yīng)的兩個(gè)index的list就可以了。
已知兩個(gè)詞各自的index的list,求最小距離的思路:
1. 分別用i住册,j兩個(gè)指針指向兩個(gè)index list的開頭。
2. 求i瓮具,j當(dāng)前指向的index的差荧飞,并判斷是否更新minDistance;
如果 i 所對(duì)應(yīng)的 index 小于 j 所對(duì)應(yīng)的 index名党,則 i++叹阔,否則 j++;(增大較小的index传睹,讓 i 和 j 所對(duì)應(yīng)的index盡量靠近耳幢,從而求出最小的distance);
3. 重復(fù)步驟2直到 i 或者 j 不再小于各自index list的長(zhǎng)度(直到越界)
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");