244. Shortest Word Distance II

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> 来存储每个单词出现的每一个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> 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 list1 = hm.get(word1);
        ArrayList 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");

你可能感兴趣的:(244. Shortest Word Distance II)