您的位置:首页 > 其它

[LeetCode244]Shortest Word Distance II

2015-11-24 07:06 375 查看
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.

Hide Company Tags LinkedIn
Hide Tags Hash Table Design
Hide Similar Problems (E) Merge Two Sorted Lists (E) Shortest Word Distance (M) Shortest Word Distance III


这道题不同之处就在于words会一直变, 而且our method will be called repeatedly. 所以我们不可能每次都copy new words list再按照 I 的方法traverse array 会超时。

unordered_map<string, vector<int>> mp
,因为可能会有duplicates 所以用vector。

O(n^2) time complexity.

class WordDistance {
public:
WordDistance(vector<string>& words) {
for(int i = 0; i<words.size(); ++i){
mp[words[i]].push_back(i);
}
}

int shortest(string word1, string word2) {
int minLen = INT_MAX;
for(int i = 0; i<mp[word1].size(); ++i){
for(int j = 0; j<mp[word2].size(); ++j){
minLen = min(abs(mp[word1][i] - mp[word2][j]), minLen);
}
}
return minLen;
}
private:
unordered_map<string,vector<int>> mp;
};

// Your WordDistance object will be instantiated and called as such:
// WordDistance wordDistance(words);
// wordDistance.shortest("word1", "word2");
// wordDistance.shortest("anotherWord1", "anotherWord2");


O(n):

class WordDistance {
public:
WordDistance(vector<string>& words) {
for(int i=0;i<words.size();i++)
wordMap[words[i]].push_back(i);
}
int shortest(string word1, string word2) {
int  i=0, j=0, dist = INT_MAX;
while(i < wordMap[word1].size() && j <wordMap[word2].size()) {
dist = min(dist, abs(wordMap[word1][i] - wordMap[word2][j]));
wordMap[word1][i]<wordMap[word2][j]?i++:j++;
}
return dist;
}
private:
unordered_map<string, vector<int>> wordMap;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode