您的位置:首页 > 其它

【LeetCode】244.Shortest Word Distance II(Medium)解题报告

2018-01-30 17:07 531 查看
【LeetCode】244.Shortest Word Distance II(Medium)解题报告

题目地址:https://leetcode.com/problems/shortest-word-distance-ii/

题目描述:

  his 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 calledrepeatedly 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.

  与前一题不同点就是重复调用的问题。

Solution:

//time:O(m*n)
//space:O(n)
class Solution{
private HashMap<String,List<Integer>> map;  //word,index(list)
public ShortestWordDistanceII(String words){
map = new HashMap<>();
for(int i=0 ; i<words.length ; i++){
if(map.containsKey(word[i])){
map.get(word[i]).add(i);
}else{
List<Integer> list = new ArrayList<>();
list.add(i);
map.put(word[i],list);
}
time:O(m*n)
public int shortest(String word1,String word2){
List<Integer> l1 = map.get(word1);
List<Integer> l2 = map.get(word2);
int res = Integer.MAX_VALUE;
for(int num1 : l1){
for(int num2 : l2){
res = Math.min(res,math.abs(num1-num2));
}
}
return res;
}

}


Solution2:

//time:O(m+n)
//space:O(n)
class Solution{
private HashMap<String,List<Integer>> map;  //word,index(list)
public ShortestWordDistanceII(String words){
map = new HashMap<>();
for(int i=0 ; i<words.length ; i++){
if(map.containsKey(word[i])){
map.get(word[i]).add(i);
}else{
List<Integer> list = new ArrayList<>();
list.add(i);
map.put(word[i],list);
}
time:O(m+n)
public int shortest(String word1,String word2){
List<Integer> l1 = map.get(word1);
List<Integer> l2 = map.get(word2);
int res = Integer.MAX_VALUE;
int i=0,j=0;
while(i<l1.size() && j<l2.size()){
res = Math.min(res,Math.abs(l1.get(i),l2.get(j));
if(l1.get(i)<l2.get(j)){
i++;
}else{
j++;
}
}
return res;
}
}


Date:2018年1月30日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode