Problem:

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.

Analysis:

This is an updated version of Shortest Word Distance.
Since it would be called many times, we should not do the search in traditional O(n) way.
One apparent thing we should optimize is to reduce uncessary check and comparision. We should exclude the words that we are not care about.
The instant idea is to use a hashmap.
Key: the word;
Value: a list of indexes associated with the word. Through this way, we can get all information we want by retrieving the HashMap, and only use two realated list.
ArrayList<Integer> list1 = map.get(word1);
ArrayList<Integer> list2 = map.get(word2); Even though we narrow down the elements we need to search, there could be a efficiency pitfall if we fail to implement it rightly. Traditionally we would try to search the shortest distance through following way.
for (int i = 0; i < list1.length(); i++) {
for (int j = 0; j < list2.length(); j++) {
min = Math.min(min, Math.abs(j - i));
}
}
Apparently, at the worst case, the time complexity is O(n^2), which is even worse than our previous solution.
Why? Cause there are many uncessary comparisions.
---------------------------------------------------------------------------------------------------------------
word 1: [1, 5, 8]
word 2: [2, 10]
Since we have already compared min with |2-1|, why we still need to compare |8-1|, since all elements after 2 must have larger distance than |2-1| (with 1 fixed). It seems I get used with "for-loop" method to scan lists, while ignoring we actually could also use "while-loop" over two lists.
-------------------------------------------------------------------
while (i < m && j < n) {
min = Math.min(min, Math.abs(list1.get(i)-list2.get(j)));
if (list1.get(i) < list2.get(j))
i++;
else
j++;
}
}
-------------------------------------------------------------------
The reason we could see the example:
word 1: [1, 5, 8]
word 2: [2, 10]
After we finished the scan: "1, 2",
"1" is no longer could have combination "1, x (x > 2)" has shorter distance than "1, 2".

Solution:

public class WordDistance {
HashMap<String, ArrayList<Integer>> map = new HashMap<String, ArrayList<Integer>> ();
public WordDistance(String[] words) {
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (map.containsKey(word)) {
map.get(word).add(i);
} else{
ArrayList<Integer> item = new ArrayList<Integer> ();
item.add(i);
map.put(word, item);
}
}
} public int shortest(String word1, String word2) {
ArrayList<Integer> list1 = map.get(word1);
ArrayList<Integer> list2 = map.get(word2);
int i = 0, j = 0;
int min = Integer.MAX_VALUE;
int m = list1.size();
int n = list2.size();
while (i < m && j < n) {
min = Math.min(min, Math.abs(list1.get(i)-list2.get(j)));
if (list1.get(i) < list2.get(j))
i++;
else
j++;
}
return min;
}
}

[LeetCode#244] Shortest Word Distance II的更多相关文章

  1. [leetcode]244. Shortest Word Distance II最短单词距离(允许连环call)

    Design a class which receives a list of words in the constructor, and implements a method that takes ...

  2. [LeetCode] 244. Shortest Word Distance II 最短单词距离 II

    This is a follow up of Shortest Word Distance. The only difference is now you are given the list of ...

  3. 244. Shortest Word Distance II

    题目: This is a follow up of Shortest Word Distance. The only difference is now you are given the list ...

  4. 【LeetCode】244. Shortest Word Distance II 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典保存出现位置 日期 题目地址:https://le ...

  5. 244. Shortest Word Distance II 实现数组中的最短距离单词

    [抄题]: Design a class which receives a list of words in the constructor, and implements a method that ...

  6. LC 244. Shortest Word Distance II 【lock, Medium】

    Design a class which receives a list of words in the constructor, and implements a method that takes ...

  7. [LC] 244. Shortest Word Distance II

    Design a class which receives a list of words in the constructor, and implements a method that takes ...

  8. [LeetCode] 243. Shortest Word Distance 最短单词距离

    Given a list of words and two words word1 and word2, return the shortest distance between these two ...

  9. [LeetCode] 245. Shortest Word Distance III 最短单词距离 III

    This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as ...

随机推荐

  1. 计算机网络-ip地址聚合后可用的地址数

    (1)59.81.1.128/28=59.81.1.1000-0000(2)59.81.1.144/28=59.81.1.1001-0000(3)59.81.1.160/28=59.81.1.1010 ...

  2. Linq转成sql后的分页方法

    sql 分页 -- Region Parametersdeclare @pageindex int set @pageindex=2set @pagesize=10 DECLARE @p0 Int = ...

  3. delphi 编写一个dos 窗体

    + //dos 仿真程序 delphi 窗体实现!   function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string ...

  4. oracle session 相关优化

    导读: 同学们是不是都用遇到过这种情况,一个业务系统开发期业务并发量只是估算一个值,而系统上线后这个并发量可能会出现溢出或是不够的   情况.在这种情况下我们DBA怎么给出合理的性能优化建议呢?本文就 ...

  5. 前端开发构建工具gulp的安装使用

    曾几何时还在使用grunt作为前端的构建工具,直到有一天同事向我推荐了gulp,在这里博主将不讨论gulp与grunt各自优势的比较,只为大家介绍gulp如何安装和使用. Gulp 是用 nodejs ...

  6. 数据库(学习整理)----7--Oracle多表查询,三种join连接

    聚合函数:(都会忽略null数据) 常用的有5种:将字段中所有的数据聚合在一条中 .sum(字段名) :求总和 .avg(字段名) :求平均值 .max(字段名) :求最大值 .min(字段名) :求 ...

  7. mysql 刘道成视频教程 第3课

    第3课: 1.mysql中条件使用关键字where: 2.查 select name,content from msg ; select name,content 控制列 where id>2 ...

  8. 网上流行的add(2)(3)(4)

    网上有很多其他的各样的算法.其实这题就可以用javascript属性arguments.callee来实现,代码如下: function add(x){ var result=0; return fu ...

  9. 正则过滤html标签

    var html = "<p>好好学习,<br>天天向上</p>"; var re=/<[^>]+>/g; var text ...

  10. FileStream读写文件流

    用FileStream 读取文件流并显示给文件内容 string p = @"C:\Users\Administrator\Desktop\1.txt"; FileStream f ...