Posted on

Description

Submission I

class Solution {
public:
    int shortestDistance(vector<string>& words, string word1, string word2) {
        unordered_map<string, vector<int>> m;
        for(int i = 0; i < words.size(); ++i) {
            m[words[i]].push_back(i);
        }
        vector<int>& index1 = m[word1];
        vector<int>& index2 = m[word2];

        int ret = INT_MAX;
        for(int i = 0; i < index1.size(); ++i) {
            for(int j = 0; j < index2.size(); ++j) {
                if(ret > abs(index1[i] - index2[j])) ret = abs(index1[i] - index2[j]); 
            }
        }
        return ret;
    }
};

Submission II

class Solution {
public:
    int shortestDistance(vector<string>& words, string word1, string word2) {
        int recent1 = -INT_MAX/2, recent2 = -INT_MAX/2, ret = INT_MAX/2;

        for(int i = 0; i < words.size(); ++i) {
            if(words[i] == word1) {
                ret = min(ret, i - recent2);
                recent1 = i;
            } else if(words[i] == word2) {
                ret = min(ret, i - recent1);
                recent2 = i;
            }
        }
        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *