当前位置:网站首页>Leetcode: Shortest Word Distance II
Leetcode: Shortest Word Distance II
2022-07-05 14:46:00 【全栈程序员站长】
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.哈希表法
复杂度
时间 O(N) 空间 O(N)
思路
因为会多次调用,我们不能每次调用的时候再把这两个单词的下标找出来。我们可以用一个哈希表,在传入字符串数组时,使用HashMap来储存word以及word在Array里面出现的index。这样当调用最短距离的方法时,我们只要遍历两个单词的下标列表就行了。具体的比较方法,则类似merge two list,每次比较两个list最小的两个值,得到一个差值。然后把较小的那个给去掉。因为我们遍历输入数组时是从前往后的,所以下标列表也是有序的。
1 public class WordDistance {
2
3 HashMap<String, ArrayList<Integer>> map;
4
5 public WordDistance(String[] words) {
6 this.map = new HashMap<String, ArrayList<Integer>>();
7 for (int i=0; i<words.length; i++) {
8 String item = words[i];
9 if (map.containsKey(item)) {
10 map.get(item).add(i);
11 }
12 else {
13 ArrayList<Integer> list = new ArrayList<Integer>();
14 list.add(i);
15 map.put(item, list);
16 }
17 }
18 }
19
20 public int shortest(String word1, String word2) {
21 ArrayList<Integer> l1 = map.get(word1);
22 ArrayList<Integer> l2 = map.get(word2);
23 int minDis = Integer.MAX_VALUE;
24 int i=0, j=0;
25 while (i<l1.size() && j<l2.size()) {
26 int p1 = l1.get(i);
27 int p2 = l2.get(j);
28 minDis = Math.min(minDis, Math.abs(p1-p2));
29 if (p1 < p2) i++;
30 else j++;
31 }
32 return minDis;
33 }
34 }
35
36 // Your WordDistance object will be instantiated and called as such:
37 // WordDistance wordDistance = new WordDistance(words);
38 // wordDistance.shortest("word1", "word2");
39 // wordDistance.shortest("anotherWord1", "anotherWord2");发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/109200.html原文链接:https://javaforall.cn
边栏推荐
- 729. My schedule I: "simulation" & "line segment tree (dynamic open point) &" block + bit operation (bucket Division) "
- 两个BI开发,3000多张报表?如何做的到?
- SSL证书错误怎么办?浏览器常见SSL证书报错解决办法
- Thymeleaf th:classappend attribute append th:styleappend style append th:data- custom attribute
- 【招聘岗位】基础设施软件开发人员
- CPU design practice - Chapter 4 practice task 3 use pre delivery technology to solve conflicts caused by related issues
- 安装配置Jenkins
- 申请代码签名证书时如何选择合适的证书品牌?
- 超级哇塞的快排,你值得学会!
- Strong connection component
猜你喜欢

How to protect user privacy without password authentication?

Selection and use of bceloss, crossentropyloss, sigmoid, etc. in pytorch classification

Pointer operation - C language

日化用品行业智能供应链协同系统解决方案:数智化SCM供应链,为企业转型“加速度”
![[detailed explanation of Huawei machine test] character statistics and rearrangement](/img/0f/972cde8c749e7b53159c9d9975c9f5.png)
[detailed explanation of Huawei machine test] character statistics and rearrangement

申请代码签名证书时如何选择合适的证书品牌?

直播预告|如何借助自动化工具落地DevOps(文末福利)

There is a powerful and good-looking language bird editor, which is better than typora and developed by Alibaba

MongDB学习笔记

【数组和进阶指针经典笔试题12道】这些题,满足你对数组和指针的所有幻想,come on !
随机推荐
【华为机试真题详解】字符统计及重排
Is the securities account given by the head teacher of qiniu school safe? Can I open an account?
Loop invariant
Structure - C language
机器学习笔记 - 灰狼优化
Selection and use of bceloss, crossentropyloss, sigmoid, etc. in pytorch classification
Mongdb learning notes
Share 20 strange JS expressions and see how many correct answers you can get
【数组和进阶指针经典笔试题12道】这些题,满足你对数组和指针的所有幻想,come on !
CPU design practice - Chapter 4 practice task 3 use pre delivery technology to solve conflicts caused by related issues
Pointer operation - C language
useMemo,memo,useRef等相关hooks详解
裁员下的上海
Thymeleaf common functions
Fonctions communes de thymeleaf
Security analysis of Web Architecture
Photoshop插件-动作相关概念-ActionList-ActionDescriptor-ActionList-动作执行加载调用删除-PS插件开发
Thymeleaf 常用函數
启牛证券账户怎么开通,开户安全吗?
漫画:优秀的程序员具备哪些属性?