[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 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的更多相关文章
- [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
题目: This is a follow up of Shortest Word Distance. The only difference is now you are given the list ...
- 【LeetCode】244. Shortest Word Distance II 解题报告 (C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典保存出现位置 日期 题目地址:https://le ...
- 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] 243. Shortest Word Distance 最短单词距离
Given a list of words and two words word1 and word2, return the shortest distance between these two ...
- [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 ...
随机推荐
- FreeBSD系统更新与软件安装方法
一.系统更新 freebsd-update fetch freebsd-update install 二.软件源更新(类似yum update.apt-get update) 1.取回源 portsn ...
- Mybatis高级应用
Mybatis是一个半自动的框架.相对于hibernate全自动模式,mybatis为开发人员提供了更加灵活的对sql语句操作的控制能力,有利于dba对相关的sql操作进行优化,同时也方便开发者构建复 ...
- HTML+CSS基础学习笔记(2)
一.无序列表标签ul <ul> <li>信息</li> <li>信息</li> ...... </ul> 代码解释:每项< ...
- vue写请求接口--请求参数的变量要在return里面声明
//谨记return里面是返回所有声明的变量的名字,数组以及对象等等 export default { data () { return { //所有的变量都是写在data 的return里面的,主要 ...
- 对 JDBC 做一个轻量封装,待完善。。。
对 JDBC 做一个轻量地封装,顺便复习,熟悉sql,io,util,lang.Reflect等包的使用,泛型的使用,待完善... package com.webproj.utils; import ...
- jquery table的隔行变色 鼠标事件
一.鼠标事件 mouseover(function(){}); 鼠标移动到目标事件 mouseout(function(){}); 鼠标离开目标的事件 二.具体应用代码 <body> &l ...
- Java MD5校验
Java 生成MD5 MD5(Message Digest Algorithm),消息摘要算法,一般用于校验文件的完整性.Java内置已经实现了MD5,与SHA1算法,利用java.security. ...
- [Twisted] 事件驱动模型
在事件驱动编程中,多个任务交替执行,并且在单一线程控制下进行.当执行I/O或者其他耗时操作时,回调函数会被注册到事件循环. 当I/O完成时,执行回调.回调函数描述了在事件完成之后,如何处理事件.事件循 ...
- 【HDU1402】【FNT版】A * B Problem Plus
Problem Description Calculate A * B. Input Each line will contain two integers A and B. Process to ...
- [Neural Networks] (Convolutional Neural Networks)CNN-卷积神经网络学习
参考:http://blog.csdn.net/zouxy09/article/details/8781543 ( 但其中有部分错误) http://ufldl.stanford.edu/wiki/i ...