[Leetcode]244. Shortest Word Distance II

这一题,综合了俩方面。
1. 数据结构的设计
2. 根据你设计的数据结构从而得到的算法。

因为会被call很多次,在constructor里面最好每个词都有一个自己的位置集合。这样可以缩短比较的数量。所以比较直观的结构就是Map<String(字符串), List<Integer>(位置集合)>
基于这样的结构,接下来的算法其实和字符串已经没什么关系,和上一题一样,比较对象其实可以是任何东西。。
这样的结构下,问题就可以解释成另一个问题:给你两个排好序的整型数数组array1,array2,找到 i in array1,j in array2, 两者的差是最小的。这题我印象里在哪见过。但不记得了 =_=。。
anyway,这种题目的做法有点像合并两个排好序的数组(链表也可以)为一个。
两个数组各自给定一个指针,ptr1, ptr2。如果array1[ptr1] > array2[ptr2],ptr2++, 反之则ptr1++。 
这个算法本质上是O(n)的,因为最坏的情况是你只有两个单词,然后各占一半,最后array1和array2走完的时候刚好是O(n)。但我真心觉得比你见到的其他的用binary search或者treemap之类的算法要来得快,因为它们是O(nlogn)的。
 

    Map<String, ArrayList<Integer>> indexMap;
    Map<String, Integer> resultCache;
    public WordDistance(String[] words) {
        indexMap = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            if (!indexMap.containsKey(words[i])) indexMap.put(words[i], new ArrayList<Integer>());
            indexMap.get(words[i]).add(i);
        }
        
        resultCache = new HashMap<>();
    }
    
    public int shortest(String word1, String word2) {
        String small = word1.compareTo(word2) < 0 ? word1 : word2;
        String large = small == word1 ? word2 : word1;
        if (resultCache.containsKey(small + large)) return resultCache.get(small + large);

        ArrayList<Integer> firstList = indexMap.get(small);
        ArrayList<Integer> secondList = indexMap.get(large);
        int result = Integer.MAX_VALUE;
        for (int i = 0, j = 0; i < firstList.size() && j < secondList.size();) {
            result = Math.min(result, Math.abs(firstList.get(i) - secondList.get(j)));
            if (firstList.get(i) < secondList.get(j)) i++;
            else j++;
        }
        
        resultCache.put(small + large, result);
        return result;
    }

这里因为它提到了repeat很多次,所以我加了一个cache。能稍微快一丢丢。。。

猜你喜欢

转载自blog.csdn.net/chaochen1407/article/details/81185776