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. 卸载RedHat7自带的yum,安装并使用网易163源

    由于redhat的yum在线更新是收费的,如果没有注册的话不能使用,如果要使用,需将redhat的yum卸载后,安装CentOS yum工具,再配置其他源,以下为详细过程: 删除redhat原有的yu ...

  2. Java代码操作HDFS(在/user/root/下面創建目錄)

    1.创建HDFS目录并打成jar包 package Hdfs; import java.io.IOException; import java.net.URI; import org.apache.h ...

  3. 定位 position

    html结构是fixed包裹relative,relative包裹absolute position:relative;相对定位 a 不影响元素本身的特性 b 不使元素脱离文档流(元素移动之后原始位置 ...

  4. struts启动报错Javassist library is missing

    很久不用struts2,最近在配置的时候,启动服务器报错 Caused by: java.lang.ExceptionInInitializerError at com.opensymphony.xw ...

  5. Android开发手记(17) 数据存储二 文件存储数据

    Android为数据存储提供了五种方式: 1.SharedPreferences 2.文件存储 3.SQLite数据库 4.ContentProvider 5.网络存储 本文主要介绍如何使用文件来存储 ...

  6. PL/SQL 访问网页(get or post方式)

    在我们开发plsql程序的过程中,有时候难免要访问一些外部网站的数据.这个时候我们就要用到utl_http包. 使用utl_http包前需要注意的是,当前的用户下是否有访问外部网络的权限. 如下是自己 ...

  7. Codevs 1082 线段树练习 3

    1082 线段树练习 3 时间限制: 3 s 空间限制: 128000 KB 题目等级 : 大师 Maste 传送门 题目描述 Description 给你N个数,有两种操作: 1:给区间[a,b]的 ...

  8. 校省选赛第一场D题TwoDecks题解

    今天晚上第二场比赛,现在还是赛后刷上次的题目,越刷越伤心,发现我赛后一次AC的功力很强大啊!!!(希望今晚变成是赛中一次AC啊!!) 好啦,回归正题. 看题目 D. Merging Two Decks ...

  9. Android 学习手札(三) 视图(View)

    在Android 系统红,任何可视化组件都需要从android.view.View类继承.可以使用两种方式创建View对象. · 一种方式是使用XML来配置View的相关属性,然后使用相应的方法来装载 ...

  10. web版扫雷小游戏(三)

    ~~~接上篇,上篇介绍了游戏实现过程中第一个比较繁琐的地方,现在展现在玩家面前的是一个有血有肉的棋盘,从某种意义上说玩家已经可以开始游戏了,但是不够人性化,玩家只能一个一个节点的点开,然后判断,然后标 ...