二刷244. Shortest Word Distance II

Medium
一开始直接clone数组居然TLE, 后来初始化的时候把shortest初始化为map.size()肯定有问题的,因为dict里面是允许duplicate的,所有你map.size()有可能是小于单词最大距离words.length的,所以得初始化为Integer.MAX_VALUE. 还有为啥不能用数组clone保持一个全局变量String[] dict来做呢,因为那样的话,每一次call shortest,都要再扫一边整个words。 虽然单词操作只是O(N), 但是当String[] words很大,call shortest的次数很多时,就会TLE.毕竟我们用map的话,只需要build一次map. 其他时候都只需要call get. 再traverse两个list, 相比下来要快很多

class WordDistance {
    Map<String, List<Integer>> map;
    public WordDistance(String[] words) {
        map = new HashMap<>();
        int index = 0;
        for (String word : words){
            if (!map.containsKey(word)){
                map.put(word, new ArrayList<Integer>(Arrays.asList(index++)));
            } else {
                map.get(word).add(index++);
            }
        }
    }

    public int shortest(String word1, String word2) {
        List<Integer> indexes1 = map.get(word1);
        List<Integer> indexes2 = map.get(word2);
        int i = 0;
        int j = 0;
        int diff = 0;
        int shortest = Integer.MAX_VALUE;
        while( i < indexes1.size() && j < indexes2.size()){
            int index1 = indexes1.get(i);
            int index2 = indexes2.get(j);
            if (index1 < index2){
                diff = index2 - index1;
                i++;
            } else {
                diff = index1 - index2;
                j++;
            }
            shortest = Math.min(shortest, diff);
        }
        return shortest;
    }
}

/**
 * Your WordDistance object will be instantiated and called as such:
 * WordDistance obj = new WordDistance(words);
 * int param_1 = obj.shortest(word1,word2);
 */
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/9231d099d6ab
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞