[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 two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters. 

Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1

 

题意:

还是数组中两个单词的最短距离。

相对于之前[leetcode]243. Shortest Word Distance最短单词距离

这题要求对于function,允许连环call(言外之意是,不能naive的扫数组了)

 

Solution1: HashMap + Merge Sort

1.  Since "method will be called repeatedly many times", it will cost much time to scan the whole input String array again and again. 

    We can use a hashmap in advance, saving each string as a key and its corresponding indices as a value.

 

2. Use pointer i, j to scan list1, list2 seperately, updating the shortest distance.

 

 

code

 1 class WordDistance {
 2     HashMap <String, List<Integer>> map;
 3     
 4     public WordDistance(String[] words) {
 5         map = new HashMap<>();
 6         for(int i = 0 ; i< words.length; i++){
 7             String w = words[i];
 8             if(map.containsKey(w)){
 9                 map.get(w).add(i);
10             }else{
11                 List<Integer> list = new ArrayList<>();
12                 list.add(i);
13                 map.put(w, list);
14             }
15         }
16         
17     }
18 
19     public int shortest(String word1, String word2) {
20         List<Integer> l1 = map.get(word1);
21         List<Integer> l2 = map.get(word2);
22         // --------------merger sort 思想  | ------------------------
23         // --------------merger sort \|/ ------------------------
24         int result = Integer.MAX_VALUE;
25         int i = 0;
26         int j = 0;
27         while(i<l1.size() && j<l2.size()) {
28             result = Math.min(result, Math.abs(l1.get(i)- l2.get(j)));
29             if(l1.get(i)<l2.get(j)){
30                 i++;
31             }else{
32                 j++;
33             }
34         }
35         // --------------merger sort------------------------
36         return result;    
37     }
38 }

 

复杂度:

时间
存储:O(N)     map是用来存储的。用时为扫一遍given array的时间。 
查找:O(m+n) list是用来查找的。用时为扫list1的时间+扫list2的时间。

空间
存储:O(N)     map是用来存储的。将whole array的元素都放入了map。 (内心OS:map的空间是由key的个数决定的)
查找:O(N)     list是用来查找的。 list所占空间为each string的corresponding 

 

转载于:https://www.cnblogs.com/liuliu5151/p/9148514.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值