LeetCode Shortest Word Distance II
原题链接在这里:https://leetcode.com/problems/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.
题解:
method 会被call好多次,没有必要每次都traverse 一遍words array. 简历一个HashMap, key是word, value是该word出现index的list.
双指针遍历word1 和 word2 两个index list 计算最小距离.
Time Complexity: Constructor WordDistance O(words.length). shortest O(list1.size()+list2.size()).
Space: O(words.length).
AC Java:
public class WordDistance { HashMap<String, List<Integer>> hm;
public WordDistance(String[] words) {
hm = new HashMap<String, List<Integer>>();
for(int i = 0; i<words.length; i++){
if(!hm.containsKey(words[i])){
List<Integer> ls = new ArrayList<Integer>();
hm.put(words[i], ls);
}
hm.get(words[i]).add(i);
}
} public int shortest(String word1, String word2) {
List<Integer> l1 = hm.get(word1);
List<Integer> l2 = hm.get(word2);
int res = Integer.MAX_VALUE;
int i = 0;
int j = 0;
while(i<l1.size() && j<l2.size()){
int index1 = l1.get(i);
int index2 = l2.get(j);
if(index1<index2){
res = Math.min(res, index2-index1);
i++;
}else{
res = Math.min(res, index1-index2);
j++;
}
}
return res;
}
} // Your WordDistance object will be instantiated and called as such:
// WordDistance wordDistance = new WordDistance(words);
// wordDistance.shortest("word1", "word2");
// wordDistance.shortest("anotherWord1", "anotherWord2");
最新文章
- 8.adr与ldr伪指令的区别
- 3.1 SharePreference
- DLUTOJ 1331 Maximum Sum
- C++中虚函数的作用浅析
- ManualResetEvent和AutoResetEvent的区别实例
- 构建高性能服务(三)Java高性能缓冲设计 vs Disruptor vs LinkedBlockingQueue--转载
- node.js模块之util模块
- HDU 1207
- eclipse kepler 创建 maven web 项目
- 在asp.net页面上按回车会触发Imagebutton控件的Click事件
- Struts2实现文件下载
- Struts2--验证框架
- Python基础【第一篇】
- Doing Homework HDU - 1074 (状压dp)
- 安装使用Entity Framework Power Tool Bate4 (Code First)从已建好的数据自动生成项目中的对应Model(新手贴,望各位大侠给予指点)
- Android中pm命令用法(转)
- 理解JavaScript模仿块作用域
- [Done]BTrace使用小记
- [Elixir002]节点启动后自动连接其它节点
- [PAT] 1144 The Missing Number(20 分)