博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode Shortest Word Distance II
阅读量:4689 次
发布时间:2019-06-09

本文共 1548 字,大约阅读时间需要 5 分钟。

原题链接在这里:

题目:

This is a follow up of . 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(1) regardless HashMap.

AC Java:

1 public class WordDistance { 2  3     HashMap
> hm; 4 public WordDistance(String[] words) { 5 hm = new HashMap
>(); 6 for(int i = 0; i
ls = new ArrayList
(); 9 hm.put(words[i], ls);10 }11 hm.get(words[i]).add(i);12 }13 }14 15 public int shortest(String word1, String word2) {16 List
l1 = hm.get(word1);17 List
l2 = hm.get(word2);18 int res = Integer.MAX_VALUE;19 int i = 0;20 int j = 0;21 while(i

跟上.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/5186304.html

你可能感兴趣的文章
SharePoint服务器端对象模型 之 使用CAML进展数据查询
查看>>
Building Tablet PC Applications ROB JARRETT
查看>>
Adobe® Reader®.插件开发
查看>>
【POJ 3461】Oulipo
查看>>
Alpha 冲刺 (5/10)
查看>>
使用Siege进行WEB压力测试
查看>>
斑马为什么有条纹?
查看>>
android多层树形结构列表学习笔记
查看>>
Android_去掉EditText控件周围橙色高亮区域
查看>>
《构建之法》第一、二、十六章阅读笔记
查看>>
Pandas基础(十一)时间序列
查看>>
arrow:让Python的日期与时间变的更好
查看>>
MySQL命令行参数
查看>>
MFC中 用Static控件做超链接(可以实现变手形、下划线、字体变色等功能)
查看>>
python 抓取小说网站,制作电子书。
查看>>
失去光标display=none事件的坑
查看>>
[LeetCode] Majority Element II
查看>>
[cocos2dx动作]CCLabel类数字变化动作
查看>>
(转)Excel的 OleDb 连接串的格式(连接Excel 2003-2013)
查看>>
Java并发编程
查看>>