题目:

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. [转]MAC下JDK版本的切换

    系统里之前先安装里jdk6的,后台又装里7,安装完成后,java -version 版本是7,  导致我eclipse打不开,一开始的做法是,把7的版本给删除掉. 删除的方法也很简单,在命令行中到 / ...

  2. hive 操作(转)

    1.命令行操作 (1)打印查询头,需要显示设置: set hive.cli.print.header=true; (2)加"--",其后的都被认为是注释,但 CLI 不解析注释.带 ...

  3. iOS中引用计数内存管理机制分析

    在 iOS 中引用计数是内存的管理方式,虽然在 iOS5 版本中,已经支持了自动引用计数管理模式,但理解它的运行方式有助于我们了解程序的运行原理,有助于 debug 程序. 操作系统的内存管理分成堆和 ...

  4. Python实战(1)

    此次实战完全按照Python教程 - 廖雪峰的官方网站进行 首先下载windows版本的Python2.7,附上下载链接http://www.python.org/ftp/python/2.7.6/p ...

  5. C# Windows - 菜单栏和工具栏

    除了MenuStrip控件之外,还有许多控件可用于填充菜单.3个常见的控件是ToolStripMenuItem,ToolStripDropDown,和ToolStripSeparator.这些控件表示 ...

  6. 64bit Ubuntu, Android AAPT, R.java

    Ubuntu 13.10 aapt: error while loading shared libraries: libstdc++.so.6: cannot open shared object f ...

  7. NodeJS -Express 4.0 用include取代partial

    在Express 4.0 下按如下方法设置: (1)运行cmd 输入:npm install express-partials -g (2)下载成功后.在app.js 中引用此插件   var par ...

  8. C# ASP .NET WEB方向和WPF方向,我该如何去选择

    一个2012年南航毕业学软件的学生,该如何去选择我的职业方向? 2011年11分月份,我被老师介绍在南京珠江路华丽国际大厦工作,开发一个大型国际物流平台,公司的开发人员比较少,设计网站的是高校的老师, ...

  9. 怎么让LinearLayout充满ScrollView

    ScrollView里只能放一个元素.    当ScrollView里的元素想填满ScrollView时,使用"fill_parent"是不管用的,必需为ScrollView设置: ...

  10. Django 学习笔记之六 建立一个简单的博客应用程序

    最近在学习django时建立了一个简单的博客应用程序,现在把简单的步骤说一下.本人的用的版本是python 2.7.3和django 1.10.3,Windows10系统 1.首先通过命令建立项目和a ...