题目:

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.

链接: http://leetcode.com/problems/shortest-word-distance-ii/

题解:

这道题是上题的follow up, 假如要多次调用应该如何优化。 我们可以维护一个HashMap<String, ArrayList<Integer>>, map里面存储每个word以及出现的坐标index。这样查询的时候我们只需要get这两个单词的list,然后进行比较就可以了。比较的时候, 因为两个list都是排序后的, 所以我们可以用类似merge two sorted list的方法来计算minDistance。

Time Complexity - O(n), Space Complexity - O(n)

public class WordDistance {
Map<String, ArrayList<Integer>> map; public WordDistance(String[] words) {
this.map = new HashMap<>();
for(int i = 0; i < words.length; i++) {
if(map.containsKey(words[i]))
map.get(words[i]).add(i);
else
map.put(words[i], new ArrayList<Integer>(Arrays.asList(i)));
}
} public int shortest(String word1, String word2) {
if(word1 == null || word2 == null)
return Integer.MAX_VALUE; List<Integer> word1s = map.get(word1);
List<Integer> word2s = map.get(word2);
int minDistance = Integer.MAX_VALUE;
int i = 0, j = 0; while(i < word1s.size() && j < word2s.size()) {
minDistance = Math.min(minDistance, Math.abs(word1s.get(i) - word2s.get(j)));
if(word1s.get(i) < word2s.get(j))
i++;
else
j++;
} return minDistance;
}
} // Your WordDistance object will be instantiated and called as such:
// WordDistance wordDistance = new WordDistance(words);
// wordDistance.shortest("word1", "word2");
// wordDistance.shortest("anotherWord1", "anotherWord2");

二刷:

还是使用了一刷的方法。主要使用一个HashMap来把每个单词出现的index保存下来,这样就避免了每次都要完整遍历整个数组。要注意取得了两个单词出现index的list之后如何操作,就是使用一个O(n)的比较来一次性遍历两个list。

之前还考虑过使用Map<String, Map<String, Integer>>来保存之前出现过的结果,但这种方法只有重复查询较多时才会更有效。

Java:

单次查找, Time Complexity - O(n), Space Complexity - O(n)

public class WordDistance {
Map<String, List<Integer>> map; public WordDistance(String[] words) {
map = new HashMap<>();
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (!map.containsKey(word)) map.put(word, new ArrayList<>());
map.get(word).add(i);
}
} public int shortest(String word1, String word2) {
List<Integer> l1 = map.get(word1);
List<Integer> l2 = map.get(word2);
int i = 0, j = 0;
int minDist = Integer.MAX_VALUE;
while (i < l1.size() && j < l2.size()) {
int idx1 = l1.get(i);
int idx2 = l2.get(j);
if (idx1 < idx2) {
minDist = Math.min(minDist, idx2 - idx1);
i++;
} else {
minDist = Math.min(minDist, idx1 - idx2);
j++;
}
}
return minDist;
}
} // Your WordDistance object will be instantiated and called as such:
// WordDistance wordDistance = new WordDistance(words);
// wordDistance.shortest("word1", "word2");
// wordDistance.shortest("anotherWord1", "anotherWord2");

Reference:

https://leetcode.com/discuss/51698/9-line-o-n-c-solution

https://leetcode.com/discuss/50190/java-solution-using-hashmap

244. Shortest Word Distance II的更多相关文章

  1. [LeetCode#244] Shortest Word Distance II

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

  2. [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 ...

  3. [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 ...

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

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

  5. 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 ...

  6. [LC] 244. Shortest Word Distance II

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

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

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

  8. [LeetCode] Shortest Word Distance II 最短单词距离之二

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

  9. LeetCode Shortest Word Distance II

    原题链接在这里:https://leetcode.com/problems/shortest-word-distance-ii/ 题目: This is a follow up of Shortest ...

随机推荐

  1. How to: Enable and Disable an Action Pane Button on a List Page [AX 2012]

    Applies To: Microsoft Dynamics AX 2012 R2, Microsoft Dynamics AX 2012 Feature Pack, Microsoft Dynami ...

  2. Ajax入门小例子

    大牛文章:http://www.cnblogs.com/guduoduo/p/3681296.html                               ---Ajax基础学习 http:/ ...

  3. Lambda(2)

    Lambda表达式是匿名方法的超集,处理匿名方法有的功能外,还有其他的功能: 1.能够推测出参数的类型,无需显示声明 2.支持语句块和表达式作为方法体 Lambda表达式的书写方式: Lambda表达 ...

  4. python 内置模块之hashlib、hmac、uuid

    一.hashlib md5和sha算法通过消息摘要算法生成定长的消息摘要,消息摘要算法是不可逆的.但同一段消息通过摘要算法后得到的值是一样的,可一通过比对消息摘要验证数据的完整性. sha算法比MD5 ...

  5. C# sogou地图API应用总结

    地图的初始化1.添加引用地图的API文件: <script src="http://api.go2map.com/maps/js/api_v2.5.1.js" type=&q ...

  6. Oracle RAC中的一台机器重启以后无法接入集群

          前天有个同事说有套AIX RAC的其中一台服务器重启了操作系统以后,集群资源CSSD的资源一直都在START的状态,检查日志输出有如下内容: [    CSSD][1286]clssnmv ...

  7. Extjs ajax form 提交

    1.form 提交 form.form.submit({ url: "/HandlerExcelToDB/UploadFile.ashx", params: {}, success ...

  8. what are Datatypes in SQLite supporting android

    As said at Datatypes In SQLite Version 3: Datatypes In SQLite Version 3 Most SQL database engines (e ...

  9. 从OGRE,GAMEPLAY3D,COCOS2D-X看开源

    OGRE,大家都很熟悉咯. 说到这一点真的有点好笑,我见过很多人说认识OGRE,但是却不知道D3D和OPENGL是什么东东的,可能是我的笑点真的很低,反正是莫名喜感.前天在COCOS2D-X的一个群里 ...

  10. 常用sqlserver语句

    1.查看表上的索引 sp_helpIndex [表名]  --查询表上拥有的索引 2.更新其它表 update 申请信息set 研发部门='123',版本信息='321'where 单号=(selec ...