题目:

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. Java 网络编程(转)

    一,网络编程中两个主要的问题 一个是如何准确的定位网络上一台或多台主机,另一个就是找到主机后如何可靠高效的进行数据传输. 在TCP/IP协议中IP层主要负责网络主机的定位,数据传输的路由,由IP地址可 ...

  2. ccache高速编译工具

    ccache的主页:http://ccache.samba.org distcc的主页:http://distcc.samba.org 1.背景: 在处理一些规模相对较大的工程时,编译花费的时间可能会 ...

  3. Linux 配置本地yum源

    Linux 配置无网络状态利用yum安装软件 在有网络的情况下安装软件只需一条yum install xxx命令,例如安装gcc只需一条指令:yum install gcc  那么在没有网络的情况下该 ...

  4. [Android Training视频系列] 8.1 Controlling Your App’s Volume and Playback

    主要内容:1 鉴别使用的是哪个音频流2 使用物理音量键控制应用程序的音量 3 使用物理播放控制键来控制应用程序的音频播放 视频讲解:http://www.eyeandroid.com/thread-1 ...

  5. ADO.NET- 基础总结及实例介绍

    最近闲暇时间写的一些小程序中,访问数据库比较多:下面主要介绍下ADO.NET方面知识,有不足之处,希望大神们不吝赐教: 提到ADO.NET,经常会和ASP.NET进行混淆,两者的区别很大,没有可比性, ...

  6. Vbox下linux虚拟机根分区扩容

    前言 使用一段时间VBox中的linux后可能会显示根分区空间不足的情况,需要扩容. 通过查阅相关资料,VBox中linux扩容主要有两种办法:通过lvm扩容和通过gparted扩容 LVM条件:VB ...

  7. c++ 信号量

    最近写了个c++项目,发现 ctrl + c 退出程序可以出发析构,但kill pid,则不会触发析构,导致现场数据丢失. 解决方案:同时捕捉以下信号. signal(SIGINT, &完成命 ...

  8. Hibernate各种主键生成策略与配置详解【附1--<generator class="foreign">】

    1.assigned 主键由外部程序负责生成,在 save() 之前必须指定一个.Hibernate不负责维护主键生成.与Hibernate和底层数据库都无关,可以跨数据库.在存储对象前,必须要使用主 ...

  9. jquery css 简单笔记

    内容 要点:清空表单中所有数据,除去 button,submit,reset,hidden 的数据 $(':input','#myform') .not(':button, :submit, :res ...

  10. mysql 常用操作

    添加用户并设置权限: grant all on *.* to root@‘%’ identified by ‘123456’with grant option; all:所有权限 select,ins ...