zoukankan      html  css  js  c++  java
  • LeetCode 244. Shortest Word Distance II

    原题链接在这里:https://leetcode.com/problems/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.

    题解:

    method 会被call好多次,没有必要每次都traverse 一遍words array. 简历一个HashMap, key是word, value是该word出现index的list.

    双指针遍历word1 和 word2 两个index list 计算最小距离.

    Time Complexity: Constructor WordDistance O(words.length). shortest O(list1.size()+list2.size()).

    Space: O(words.length).

    AC Java:

     1 public class WordDistance {
     2 
     3     HashMap<String, List<Integer>> hm;
     4     public WordDistance(String[] words) {
     5         hm = new HashMap<String, List<Integer>>();
     6         for(int i = 0; i<words.length; i++){
     7             if(!hm.containsKey(words[i])){
     8                 List<Integer> ls = new ArrayList<Integer>();
     9                 hm.put(words[i], ls);
    10             }
    11             hm.get(words[i]).add(i);
    12         }
    13     }
    14 
    15     public int shortest(String word1, String word2) {
    16         List<Integer> l1 = hm.get(word1);
    17         List<Integer> l2 = hm.get(word2);
    18         int res = Integer.MAX_VALUE;
    19         int i = 0;
    20         int j = 0;
    21         while(i<l1.size() && j<l2.size()){
    22             int index1 = l1.get(i);
    23             int index2 = l2.get(j);
    24             if(index1<index2){
    25                 res = Math.min(res, index2-index1);
    26                 i++;
    27             }else{
    28                 res = Math.min(res, index1-index2);
    29                 j++;
    30             }
    31         }
    32         return res;
    33     }
    34 }
    35 
    36 // Your WordDistance object will be instantiated and called as such:
    37 // WordDistance wordDistance = new WordDistance(words);
    38 // wordDistance.shortest("word1", "word2");
    39 // wordDistance.shortest("anotherWord1", "anotherWord2");

    类似Shortest Word Distance.

    跟上Shortest Word Distance III.

  • 相关阅读:
    使用cd回到上次编辑的目录
    自动机编程
    python日常题目小练习
    python中的循环结构等相关知识
    python中的数学类型及操作
    小白艰难的Python图像的绘制
    小白的第二天之计算机基础及软件安装
    小白的日常练习
    小白的第一天
    协程
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5186304.html
Copyright © 2011-2022 走看看