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 ...
随机推荐
- perl中shift 和unshift 操作
##################################################################### unshift 和shift 对一个数组的开头进行操作(数组 ...
- c++继承详解
C++中的三种继承public,protected,private 三种访问权限 public:可以被任意实体访问 protected:只允许子类及本类的成员函数访问 private:只允许本类的成员 ...
- innobackupex:Error:xtrabackup child process has died at /usr/bin/innobackupex
使用innobackupex进行数据库备份,报如下错误:innobackupex --compress --parallel=4 --user=root --password=yoon /expo ...
- Linux环境下GIT初次使用
Git是一个功能强大的分布式版本控制系统,最初用来作Linux内核代码管理的. 第一次接触到github是关于一个报道:在2013年1月15日晚间,全球最大的社交编程及代码托管网站GitHub突然疑似 ...
- elipse+pydev+python开发arcgis脚本程序
环境配置参考:http://www.cnblogs.com/halfacre/archive/2012/07/22/2603848.html 添加arcpy类库.arctoolbox.arcgis-b ...
- Leeo 智能夜灯:默默守护你的家
http://www.ifanr.com/462377 Leeo 智能夜灯是一个低调的设备.它不需要你与之交互,也不会产生多余的费用.当你把它插到墙上插座,然后下载应用后,就不用再管它了.然后,它就开 ...
- iOS下日期的处理(世界标准时转本地时间)
NSDate存储的是世界标准时(UTC),输出时需要根据时区转换为本地时间 Dates NSDate类提供了创建date,比较date以及计算两个date之间间隔的功能.Date对象是 ...
- .NET中 MEF应用于IOC
IOC解释 IOC,控制反转的意思.所谓依赖,从程序的角度看,就是比如A要调用B的方法,那么A就依赖于B,反正A要用到B,则A依赖于B.所谓反转,你必须理解如果不反转,会怎么着,因为A必须要有B,才可 ...
- NOIP2015-stone(二分答案)
这道题在考试时二分答案写炸了,结果得了20分.....同学有用贪心写的(对,贪心!!)都得了30,我感到了深深的恶意.这段时间在忙转语言,现在重新整理一下NOIP的题. 题目来源:vijos 题目如下 ...
- Codeforces Round #331 (Div. 2) C. Wilbur and Points
C. Wilbur and Points time limit per test 2 seconds memory limit per test 256 megabytes input standar ...