244. Shortest Word Distance II
题目:
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的更多相关文章
- [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 ...
- [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 ...
- [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 ...
- 244. Shortest Word Distance II 实现数组中的最短距离单词
[抄题]: Design a class which receives a list of words in the constructor, and implements a method that ...
- 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 ...
- [LC] 244. Shortest Word Distance II
Design a class which receives a list of words in the constructor, and implements a method that takes ...
- 【LeetCode】244. Shortest Word Distance II 解题报告 (C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典保存出现位置 日期 题目地址:https://le ...
- [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 ...
- LeetCode Shortest Word Distance II
原题链接在这里:https://leetcode.com/problems/shortest-word-distance-ii/ 题目: This is a follow up of Shortest ...
随机推荐
- 第25章 项目6:使用CGI进行远程编辑
初次实现 25-1 simple_edit.cgi --简单的网页编辑器 #!D:\Program Files\python27\python.exeimport cgiform = cgi.Fiel ...
- javascript和jquery 获取触发事件的元素
一个很简单的问题,却因为大意,经常忘了处理,导致程序运行出错. <!DOCTYPE html> <html> <head> <meta charset=&qu ...
- COALESCE在SQL拼接中的大用途
SQL拼接可以使得代码比较灵活,不会那么死板,对于维护也比较方便. 下面是简单的SQL拼接,同时也包含了隐式游标的概念吧,可以遍历表中的每一个字段 -------------------------- ...
- git,repo学习
Repo:就是一组git命令的集合,repo init 下载一个分支. repo start 文件名 --all本地传建的另一个代码分支,用于备份作用. 比如:repo start zhao --al ...
- Export Farm Solution wsp Files SharePoint 2007 and 2010
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")$farm = [Microsof ...
- tomcat 7 用mod_jk做 负载均衡
在Win7中使用apache为tomcat做负载均衡,各组件及版本如下: 两个tomcat v 7.0.57 一个apache v 2.2.14 一个mod_jk v 1.2.33(for windo ...
- bnuoj 4207 台风(模拟题)
http://www.bnuoj.com/bnuoj/problem_show.php?pid=4207 [题意]:中文题,略 [题解]:模拟 [code]: #include <iostrea ...
- 谈谈php中上传文件的处理
这是一个表单的时代... 我们在浏览器中编辑自己的信息,会遇到上传头像:在文库中,我们会上传文档......到处存在“上传”这个词. php是最好的语言(其他语言的程序猿们不要打我...).php在处 ...
- html+css学习笔记 5[表格、表单]
表格 -- 默认样式重置 表格标签: table 表格 thead 表格头 tbody 表格主体 tfoot 表格尾 tr 表格行 th 元素定义表头 ...
- c++ 函数返回指针 及用法
#include<string> #include<iostream> using namespace std; string fun1(int a) { string str ...