当前位置:网站首页>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
边栏推荐
- Security analysis of Web Architecture
- webRTC SDP mslabel lable
- 想问下大家伙,有无是从腾讯云MYSQL同步到其他地方的呀?腾讯云MySQL存到COS上的binlog
- be careful! Software supply chain security challenges continue to escalate
- 启牛证券账户怎么开通,开户安全吗?
- 超级哇塞的快排,你值得学会!
- Run faster with go: use golang to serve machine learning
- Disjoint Set
- 【NVMe2.0b 14-9】NVMe SR-IOV
- Drive brushless DC motor based on Ti drv10970
猜你喜欢

How does redis implement multiple zones?

Mongdb learning notes

乌卡时代下,企业供应链管理体系的应对策略

Under the crisis of enterprise development, is digital transformation the future savior of enterprises

Implement a blog system -- using template engine technology

计算中间件 Apache Linkis参数解读

leetcode:881. 救生艇

Talking about how dataset and dataloader call when loading data__ getitem__ () function

How can non-technical departments participate in Devops?

Thymeleaf th:classappend属性追加 th:styleappend样式追加 th:data-自定义属性
随机推荐
easyOCR 字符識別
CPU设计实战-第四章实践任务二用阻塞技术解决相关引发的冲突
I want to inquire about how to ensure data consistency when a MySQL transaction updates multiple tables?
[learning notes] connectivity and circuit of graph
Two policemen were shot dead in a "safety accident" in Philadelphia, USA
我这边同时采集多个oracle表,采集一会以后,会报oracle的oga内存超出,大家有没有遇到的?
外盘入金都不是对公转吗,那怎么保障安全?
[detailed explanation of Huawei machine test] happy weekend
CyCa children's physical etiquette Ningbo training results assessment came to a successful conclusion
Type declaration of all DOM elements in TS
Selection and use of bceloss, crossentropyloss, sigmoid, etc. in pytorch classification
Disjoint Set
Section - left closed right open
Thymeleaf 常用函數
World Environment Day | Chow Tai Fook serves wholeheartedly to promote carbon reduction and environmental protection
【学习笔记】图的连通性与回路
Total amount analysis accounting method and potential method - allocation analysis
Thymeleaf th:classappend attribute append th:styleappend style append th:data- custom attribute
详解Vue适时清理keepalive缓存方案
How to solve the problem of garbled code when installing dependency through NPM or yarn