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. CentOS 6.7 配置nginx支持SSL/https访问

    一.安装必要的包 yum install openssl openssl-devel 二.配置编译参数,增加对SSL的支持 ./configure –with-http_ssl_module 三.修改 ...

  2. Spring各种传播特性源码实现的概览

    这几天都在分析Spring的源码实现,看到事务管理的部分 我们知道事务的传播特性有下面几种,我标黄的就是最常用的3中传播特性, Sping在发生事务嵌套的时候,会依据内层事务的传播特性,来决定内层是事 ...

  3. 模版引擎(NVelocity)开发

    在net中用模版开发,在handler中用到了大量的html代码.为解决这个问题,我可以采用模版引擎(NVelocity)进行开发.1.首先需要将NVelocity.dll文件放入项目,其次引用.2. ...

  4. bootstap 滚动监听

    ---首先结合源代码介绍官网的说明 ---然后总结了使用滚动监听的几个步骤 ---最后给出一个简单的例子 ---关键的一点:整体有点零散和乱七八糟,辛苦你的思维和眼睛了,呵呵 ------------ ...

  5. 初学HTML5系列一:简单介绍

    最近很闲,就想着学点东西,然后就瞄中了html5,以前只看过很简单的一些,这次是系统的学下,顺便也记录下.废话不多说,开始正题. 稍微介绍下html5,html5是W3C和WHATWG 合作的结果. ...

  6. asp.net 操作INI文件的读写,读写操作本地ini配置文件

    using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Secu ...

  7. phpmyadmin备份小问题

    不要将imformation——shame或者mysql等备份,要有选择的备份表 关注我的新浪微博

  8. Net的struct的内存对齐问题

    很少有人谈起struct的内存对齐问题, 就是在很多C#书中, 也很少提及. 但在实际应用中, 如果不注意内存对齐, struct比较大的话, 则会浪费一定的内存.    先从一个实例看起. publ ...

  9. C++专题 - 修练8年C++面向对象程序设计之体会 林锐

    六年前,我刚热恋“面向对象”(Object-Oriented)时,一口气记住了近十个定义.六年后,我从几十万行程序中滚爬出来准备写点心得体会时, 却无法解释什么是“面向对象”,就象说不清楚什么是数学那 ...

  10. PHP 单一入口

    单一入口概述 单一入口的应用程序就是说用一个文件处理所有的HTTP请求,例如不管是列表页还是文章页,都是从浏览器访问index.php文件,这个文件就是这个应用程序的单一入口. 打个比方,大家都要上W ...