[LeetCode245] Shortest Word Distance III

This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

word1 and word2 may be the same and they represent two individual words in the list.

For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “makes”, word2 = “coding”, return 1.
Given word1 = "makes", word2 = "makes", return 3.

Note:
You may assume word1 and word2 are both in the list.

Hide Company Tags LinkedIn
Hide Tags Array
Hide Similar Problems (E) Shortest Word Distance (M) Shortest Word Distance II

这道题word1和2可能是一样的了,也就是duplicates之间的距离不是自己跟自己的距离。

然后就由II想到一个慢方法:O(n) time with O(n) memory;

class Solution {
public:
    int shortestWordDistance(vector<string>& words, string word1, string word2) {
        //too slooow....
        unordered_map<string, vector<int> > mp;
        for(int i = 0; i < words.size(); ++i) mp[words[i]].push_back(i);
        int pos1 = 0, pos2 = 0, minLen = INT_MAX;
        if(word1 != word2){
            for(int i = 0; i<mp[word1].size(); ++i){
                for(int j = 0; j< mp[word2].size(); ++j){
                    minLen = min(minLen, abs(mp[word1][i] - mp[word2][j]));
                }
            }
        }else{
            for(int i = 1; i<mp[word1].size(); ++i){
                minLen = min(minLen, abs(mp[word1][i] - mp[word1][i-1]));
            }
        }
        return minLen;
    }
};

参考了大家的O(n) time w/ O(1) space, 太感慨了。。

class Solution {
public:
    int shortestWordDistance(vector<string>& words, string word1, string word2) {
    int n = words.size();
        int res = n, l = n, r = -n;
        for (int i=0; i<words.size(); i++) {
            if (words[i] == word1)
                l = (word1==word2)?r:i;
            if (words[i] == word2) 
                r = i;
            res = min(res, abs(l-r));
        }
        return res;
    }
};

你可能感兴趣的:(LeetCode)