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

Example:

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

Input: word1 = “coding”, word2 = “practice”
Output: 3

Note:
You may assume that word1 does not equal to word2, and_word1_and_word2_are both in the list.

遍历一遍array,记录出现的word1和word2的index,每次更新最短距离

class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        int i1 = -1;
        int i2 = -1;
        int res = words.length - 1;

        for(int i = 0; i < words.length; i++) {
            if(words[i].equals(word1)) {
                i1 = i;

                if(i2 != -1)
                    res = Math.min(res, i1 - i2);
            }

            if(words[i].equals(word2)) {
                i2 = i;

                if(i1 != -1)
                    res = Math.min(res, i2 - i1);
            }
        }

        return res;
    }
}

results matching ""

    No results matching ""