Monday, December 28, 2015

244. Shortest Word Distance II ---------M

Q:
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 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.


A:
就是保持2个list,然后对比
这里唯一需要注意的是:每次根据 index的值,来update 前进哪个index

class WordDistance {
public:
    WordDistance(vector<string>& words) {
        for(int i =0;i<words.size();i++){
            M[words[i]].push_back(i);
        }
    }
    
    int shortest(string word1, string word2) {
        vector<int> &V1 = M[word1];
        vector<int> &V2 = M[word2];
        int res = INT_MAX;
        for(int i1 = 0, i2=0;i1<V1.size();i1++){
            int a = V1[i1];
            int b = V2[i2];
            res = min(res, abs(a-b));
            if(a>b){
                if(i2+1<V2.size()){
                    i2++;
                    i1--;
                }
            }
        }
        return res;
    }
private:
    unordered_map<string, vector<int>> M;
};

/**
 * Your WordDistance object will be instantiated and called as such:
 * WordDistance* obj = new WordDistance(words);
 * int param_1 = obj->shortest(word1,word2);
 */

Mistakes:



No comments:

Post a Comment