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.

  • 相关阅读:
    在linux下的使用复制命令cp,不让出现“overwrite”(文件覆盖)提示的方法。【转】
    Java 学习 day05
    Java 学习 day04
    Java 学习 day03
    Java 学习 day02
    Java 学习 day01
    学习TensorFlow,TensorBoard可视化网络结构和参数
    自编码器及相关变种算法简介
    自编码器(autoencoder)
    卷积神经网络
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5186304.html
Copyright © 2011-2022 走看看