243. Shortest Word Distance

Given a list of words and two wordsword1andword2, return the shortest distance between these two words in the list.
For example,
Assume that words =["practice", "makes", "perfect", "coding", "makes"].
Givenword1=“coding”,word2=“practice”, return 3.
Givenword1="makes",word2="coding", return 1.
Note:You may assume thatword1does not equal toword2, andword1andword2are both in the list.

min的计算放到if里大大减少判断次数, 也提高了运行效率。

public int shortestDistance(String[] words, String word1, String word2) {
       int pos1 = -1;
       int pos2 = -1;
       int min = Integer.MAX_VALUE;
       for(int i = 0; i < words.length; i++){
                if(words[i].equals(word1)){
                       pos1 = i;
                       if(pos1 != -1 && pos2 != -1){
                               min = Math.min(min, Math.abs(pos1 - pos2));
                       }
                 }else if(words[i].equals(word2)){
                        pos2 = i;
                        if(pos1 != -1 && pos2 != -1){
                                  min = Math.min(min, Math.abs(pos1 - pos2));
                        }
                 }
       }
       return min;
}

你可能感兴趣的:(243. Shortest Word Distance)