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.

思路

因为会多次调用,就要考虑节省时间复杂度。我们不能每次调用的时候再把这两个单词的下标找出来。我们可以用一个哈希表,在传入字符串数组时,就把每个单词的下标找出存入表中。这样当调用最短距离的方法时,我们只要遍历两个单词的下标列表就行了。具体的比较方法,则类似merge two list,每次比较两个list最小的两个值,得到一个差值。然后把较小的那个给去掉。因为我们遍历输入数组时是从前往后的,所以下标列表也是有序的。

问题一:为何在指针 i 和 j 扫 list2 的时候,是

            if(list1.get(i) < list2.get(j)) {
                i++;
            } else {            
                j++;
            }

思路类似以下这个题的解法思路

//Merge Two Sorted Lists
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        if(l1 == NULL) return l2;
        if(l2 == NULL) return l1;

        if(l1->val < l2->val) {
            l1->next = mergeTwoLists(l1->next, l2);
            return l1;
        } else {
            l2->next = mergeTwoLists(l2->next, l1);
            return l2;
        }
    }

分析

  1. Since the functionshortestwill be called repeatedly, we need to use more space in trade of less time. It's not wise to use two pointer's method sweeping the array again and agian, because it is time-consuming.

  2. We can use a hash table mapping word to index list.

  3. Then the function shortest() is just to find the minimum difference between two sorted lists

图解

复杂度

The time complexity is O(m+n) where m and n are the lengths of list1 and list2.

代码

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;    
    }
}

results matching ""

    No results matching ""