C++ easy understand solution


  • 3
    M
    int shortestDistance(vector<string>& words, string word1, string word2) {
        int id1 = -1, id2 = -1;
        int minDist = INT_MAX;
        for (int i = 0; i < words.size(); i++) {
            if (words[i] == word1) {
                id1 = i;
                if (id2 != -1) {
                    minDist = min(minDist, id1 - id2);
                }
            } else if (words[i] == word2) {
                id2 = i;
                if (id1 != -1) {
                    minDist = min(minDist, id2 - id1);
                }
            }
        }
        return minDist;
    }

  • 0
    Z

    Same idea

    int shortestDistance(vector<string>& words, string word1, string word2) {
        int index1 = -1, index2 = -1, min_distance = INT_MAX;
        for(int i = 0; i < words.size(); ++i){
            if(words[i].compare(word1) == 0)
                index1 = i;
            else if(words[i].compare(word2) == 0)
                index2 = i;
            else continue;
            if(index1 != -1 && index2 != -1)
                min_distance = min(min_distance, abs(index1 - index2));
        }
        return min_distance;
    }

  • 0
    Y

    Little optimization: you can check when min distance is 1, then return the result.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.